diff --git a/.travis.yml b/.travis.yml index 683422dc97..5e86714a89 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,7 @@ before_install: - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc install: skip -script: travis_wait 60 mvn -q install -Pdefault-first,default-second +script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true sudo: required diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java index cb476b9d9e..a50028a9ae 100644 --- a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java +++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java @@ -28,14 +28,14 @@ public class Log { System.out.println("Had " + count + " commits overall on current branch"); logs = git.log() - .add(repository.resolve("remotes/origin/testbranch")) + .add(repository.resolve(git.getRepository().getFullBranch())) .call(); count = 0; for (RevCommit rev : logs) { System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); count++; } - System.out.println("Had " + count + " commits overall on test-branch"); + System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); logs = git.log() .all() diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java index ed7168b2c2..ad34890996 100644 --- a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java @@ -1,3 +1,5 @@ +package com.baeldung.jgit; + import com.baeldung.jgit.helper.Helper; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectReader; diff --git a/akka-http/pom.xml b/akka-http/pom.xml new file mode 100644 index 0000000000..51e70fb583 --- /dev/null +++ b/akka-http/pom.xml @@ -0,0 +1,48 @@ + + + + 4.0.0 + akka-http + akka-http + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + com.typesafe.akka + akka-http_2.12 + ${akka.http.version} + + + com.typesafe.akka + akka-stream_2.12 + 2.5.11 + + + com.typesafe.akka + akka-http-jackson_2.12 + ${akka.http.version} + + + com.typesafe.akka + akka-http-testkit_2.12 + ${akka.http.version} + test + + + + + UTF-8 + UTF-8 + 1.8 + 10.0.11 + 2.5.11 + + diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/User.java b/akka-http/src/main/java/com/baeldung/akkahttp/User.java new file mode 100644 index 0000000000..43c21eca62 --- /dev/null +++ b/akka-http/src/main/java/com/baeldung/akkahttp/User.java @@ -0,0 +1,26 @@ +package com.baeldung.akkahttp; + +public class User { + + private final Long id; + + private final String name; + + public User() { + this.name = ""; + this.id = null; + } + + public User(Long id, String name) { + this.name = name; + this.id = id; + } + + public String getName() { + return name; + } + + public Long getId() { + return id; + } +} \ No newline at end of file diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java new file mode 100644 index 0000000000..431014a88b --- /dev/null +++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java @@ -0,0 +1,41 @@ +package com.baeldung.akkahttp; + +import akka.actor.AbstractActor; +import akka.actor.Props; +import akka.japi.pf.FI; +import com.baeldung.akkahttp.UserMessages.ActionPerformed; +import com.baeldung.akkahttp.UserMessages.CreateUserMessage; +import com.baeldung.akkahttp.UserMessages.GetUserMessage; + + +class UserActor extends AbstractActor { + + private UserService userService = new UserService(); + + static Props props() { + return Props.create(UserActor.class); + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match(CreateUserMessage.class, handleCreateUser()) + .match(GetUserMessage.class, handleGetUser()) + .build(); + } + + private FI.UnitApply handleCreateUser() { + return createUserMessageMessage -> { + userService.createUser(createUserMessageMessage.getUser()); + sender().tell(new ActionPerformed(String.format("User %s created.", createUserMessageMessage.getUser() + .getName())), getSelf()); + }; + } + + private FI.UnitApply handleGetUser() { + return getUserMessageMessage -> { + sender().tell(userService.getUser(getUserMessageMessage.getUserId()), getSelf()); + }; + } + +} diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserMessages.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserMessages.java new file mode 100644 index 0000000000..995b92bcb0 --- /dev/null +++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserMessages.java @@ -0,0 +1,49 @@ +package com.baeldung.akkahttp; + +import java.io.Serializable; + +public interface UserMessages { + + class ActionPerformed implements Serializable { + + private static final long serialVersionUID = 1L; + + private final String description; + + public ActionPerformed(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + } + + class CreateUserMessage implements Serializable { + + private static final long serialVersionUID = 1L; + private final User user; + + public CreateUserMessage(User user) { + this.user = user; + } + + public User getUser() { + return user; + } + } + + class GetUserMessage implements Serializable { + private static final long serialVersionUID = 1L; + private final Long userId; + + public GetUserMessage(Long userId) { + this.userId = userId; + } + + public Long getUserId() { + return userId; + } + } + +} diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserServer.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserServer.java new file mode 100644 index 0000000000..0c1dbd1f60 --- /dev/null +++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserServer.java @@ -0,0 +1,70 @@ +package com.baeldung.akkahttp; + +import java.util.Optional; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.TimeUnit; + +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.http.javadsl.marshallers.jackson.Jackson; +import akka.http.javadsl.model.StatusCodes; +import akka.http.javadsl.server.HttpApp; +import akka.http.javadsl.server.Route; +import akka.pattern.PatternsCS; +import akka.util.Timeout; +import com.baeldung.akkahttp.UserMessages.ActionPerformed; +import com.baeldung.akkahttp.UserMessages.CreateUserMessage; +import com.baeldung.akkahttp.UserMessages.GetUserMessage; +import scala.concurrent.duration.Duration; +import static akka.http.javadsl.server.PathMatchers.*; + +class UserServer extends HttpApp { + + private final ActorRef userActor; + + Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS)); + + UserServer(ActorRef userActor) { + this.userActor = userActor; + } + + @Override + public Route routes() { + return path("users", this::postUser) + .orElse(path(segment("users").slash(longSegment()), id -> + route(getUser(id)))); + } + + private Route getUser(Long id) { + return get(() -> { + CompletionStage> user = PatternsCS.ask(userActor, new GetUserMessage(id), timeout) + .thenApply(obj -> (Optional) obj); + + return onSuccess(() -> user, performed -> { + if (performed.isPresent()) + return complete(StatusCodes.OK, performed.get(), Jackson.marshaller()); + else + return complete(StatusCodes.NOT_FOUND); + }); + }); + } + + private Route postUser() { + return route(post(() -> entity(Jackson.unmarshaller(User.class), user -> { + CompletionStage userCreated = PatternsCS.ask(userActor, new CreateUserMessage(user), timeout) + .thenApply(obj -> (ActionPerformed) obj); + + return onSuccess(() -> userCreated, performed -> { + return complete(StatusCodes.CREATED, performed, Jackson.marshaller()); + }); + }))); + } + + public static void main(String[] args) throws Exception { + ActorSystem system = ActorSystem.create("userServer"); + ActorRef userActor = system.actorOf(UserActor.props(), "userActor"); + UserServer server = new UserServer(userActor); + server.startServer("localhost", 8080, system); + } + +} diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserService.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserService.java new file mode 100644 index 0000000000..50dc1e1b28 --- /dev/null +++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserService.java @@ -0,0 +1,35 @@ +package com.baeldung.akkahttp; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class UserService { + + private final static List users = new ArrayList<>(); + + static { + users.add(new User(1l, "Alice")); + users.add(new User(2l, "Bob")); + users.add(new User(3l, "Chris")); + users.add(new User(4l, "Dick")); + users.add(new User(5l, "Eve")); + users.add(new User(6l, "Finn")); + } + + public Optional getUser(Long id) { + return users.stream() + .filter(user -> user.getId() + .equals(id)) + .findFirst(); + } + + public void createUser(User user) { + users.add(user); + } + + public List getUsers(){ + return users; + } + +} diff --git a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java new file mode 100644 index 0000000000..1170a2d761 --- /dev/null +++ b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.akkahttp; + +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.http.javadsl.model.ContentTypes; +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.Test; + +public class UserServerUnitTest extends JUnitRouteTest { + + ActorSystem system = ActorSystem.create("helloAkkaHttpServer"); + + ActorRef userActorRef = system.actorOf(UserActor.props(), "userActor"); + + TestRoute appRoute = testRoute(new UserServer(userActorRef).routes()); + + @Test + public void whenRequest_thenActorResponds() { + + appRoute.run(HttpRequest.GET("/users/1")) + .assertEntity(alice()) + .assertStatusCode(200); + + appRoute.run(HttpRequest.GET("/users/42")) + .assertStatusCode(404); + + appRoute.run(HttpRequest.DELETE("/users/1")) + .assertStatusCode(200); + + appRoute.run(HttpRequest.DELETE("/users/42")) + .assertStatusCode(200); + + appRoute.run(HttpRequest.POST("/users") + .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, zaphod()))) + .assertStatusCode(201); + + } + + private String alice() { + return "{\"id\":1,\"name\":\"Alice\"}"; + } + + private String zaphod() { + return "{\"id\":42,\"name\":\"Zaphod\"}"; + } + +} diff --git a/algorithms-genetic/pom.xml b/algorithms-genetic/pom.xml index 2a10a81980..fc6d36dac1 100644 --- a/algorithms-genetic/pom.xml +++ b/algorithms-genetic/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung algorithms-genetic 0.0.1-SNAPSHOT - + algorithms-genetic + com.baeldung parent-modules @@ -61,4 +61,5 @@ 1.11 - \ No newline at end of file + + diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md index a04874c4d2..a725bbd141 100644 --- a/algorithms-miscellaneous-1/README.md +++ b/algorithms-miscellaneous-1/README.md @@ -10,4 +10,6 @@ - [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm) - [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms) - [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters) -- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element) \ No newline at end of file +- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element) +- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial) +- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings) \ No newline at end of file diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index 16749d452e..5006670dd9 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung algorithms-miscellaneous-1 0.0.1-SNAPSHOT - + algorithms-miscellaneous-1 + com.baeldung parent-modules @@ -17,6 +17,11 @@ commons-math3 ${commons-math3.version} + + com.google.guava + guava + ${guava.version} + commons-codec commons-codec @@ -73,6 +78,7 @@ 3.6.1 3.9.0 1.11 + 25.1-jre \ No newline at end of file diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java new file mode 100644 index 0000000000..43d2221773 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java @@ -0,0 +1,63 @@ +package com.baeldung.algorithms.factorial; + +import java.math.BigInteger; +import java.util.stream.LongStream; + +import org.apache.commons.math3.util.CombinatoricsUtils; + +import com.google.common.math.BigIntegerMath; + +public class Factorial { + + public long factorialUsingForLoop(int n) { + long fact = 1; + for (int i = 2; i <= n; i++) { + fact = fact * i; + } + return fact; + } + + public long factorialUsingStreams(int n) { + return LongStream.rangeClosed(1, n) + .reduce(1, (long x, long y) -> x * y); + } + + public long factorialUsingRecursion(int n) { + if (n <= 2) { + return n; + } + return n * factorialUsingRecursion(n - 1); + } + + private Long[] factorials = new Long[20]; + + public long factorialUsingMemoize(int n) { + + if (factorials[n] != null) { + return factorials[n]; + } + + if (n <= 2) { + return n; + } + long nthValue = n * factorialUsingMemoize(n - 1); + factorials[n] = nthValue; + return nthValue; + } + + public BigInteger factorialHavingLargeResult(int n) { + BigInteger result = BigInteger.ONE; + for (int i = 2; i <= n; i++) + result = result.multiply(BigInteger.valueOf(i)); + return result; + } + + public long factorialUsingApacheCommons(int n) { + return CombinatoricsUtils.factorial(n); + } + + public BigInteger factorialUsingGuava(int n) { + return BigIntegerMath.factorial(n); + } + +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java new file mode 100644 index 0000000000..cd1f3e94d5 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java @@ -0,0 +1,54 @@ +package com.baeldung.algorithms.string; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class LongestSubstringNonRepeatingCharacters { + + public static String getUniqueCharacterSubstringBruteForce(String input) { + String output = ""; + for (int start = 0; start < input.length(); start++) { + Set visited = new HashSet<>(); + int end = start; + for (; end < input.length(); end++) { + char currChar = input.charAt(end); + if (visited.contains(currChar)) { + break; + } else { + visited.add(currChar); + } + } + if (output.length() < end - start + 1) { + output = input.substring(start, end); + } + } + return output; + } + + public static String getUniqueCharacterSubstring(String input) { + Map visited = new HashMap<>(); + String output = ""; + for (int start = 0, end = 0; end < input.length(); end++) { + char currChar = input.charAt(end); + if (visited.containsKey(currChar)) { + start = Math.max(visited.get(currChar) + 1, start); + } + if (output.length() < end - start + 1) { + output = input.substring(start, end + 1); + } + visited.put(currChar, end); + } + return output; + } + + public static void main(String[] args) { + if(args.length > 0) { + System.out.println(getUniqueCharacterSubstring(args[0])); + } else { + System.err.println("This program expects command-line input. Please try again!"); + } + } + +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java new file mode 100644 index 0000000000..b3d142eb07 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java @@ -0,0 +1,90 @@ +package com.baeldung.algorithms.string; + +import java.util.HashSet; +import java.util.Set; + +public class SubstringPalindrome { + + public Set findAllPalindromesUsingCenter(String input) { + final Set palindromes = new HashSet<>(); + if (input == null || input.isEmpty()) { + return palindromes; + } + if (input.length() == 1) { + palindromes.add(input); + return palindromes; + } + for (int i = 0; i < input.length(); i++) { + palindromes.addAll(findPalindromes(input, i, i + 1)); + palindromes.addAll(findPalindromes(input, i, i)); + } + return palindromes; + } + + private Set findPalindromes(String input, int low, int high) { + Set result = new HashSet<>(); + while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) { + result.add(input.substring(low, high + 1)); + low--; + high++; + } + return result; + } + + public Set findAllPalindromesUsingBruteForceApproach(String input) { + Set palindromes = new HashSet<>(); + if (input == null || input.isEmpty()) { + return palindromes; + } + if (input.length() == 1) { + palindromes.add(input); + return palindromes; + } + for (int i = 0; i < input.length(); i++) { + for (int j = i + 1; j <= input.length(); j++) + if (isPalindrome(input.substring(i, j))) { + palindromes.add(input.substring(i, j)); + } + } + return palindromes; + } + + private boolean isPalindrome(String input) { + StringBuilder plain = new StringBuilder(input); + StringBuilder reverse = plain.reverse(); + return (reverse.toString()).equals(input); + } + + public Set findAllPalindromesUsingManachersAlgorithm(String input) { + Set palindromes = new HashSet<>(); + String formattedInput = "@" + input + "#"; + char inputCharArr[] = formattedInput.toCharArray(); + int max; + int radius[][] = new int[2][input.length() + 1]; + for (int j = 0; j <= 1; j++) { + radius[j][0] = max = 0; + int i = 1; + while (i <= input.length()) { + palindromes.add(Character.toString(inputCharArr[i])); + while (inputCharArr[i - max - 1] == inputCharArr[i + j + max]) + max++; + radius[j][i] = max; + int k = 1; + while ((radius[j][i - k] != max - k) && (k < max)) { + radius[j][i + k] = Math.min(radius[j][i - k], max - k); + k++; + } + max = Math.max(max - k, 0); + i += k; + } + } + for (int i = 1; i <= input.length(); i++) { + for (int j = 0; j <= 1; j++) { + for (max = radius[j][i]; max > 0; max--) { + palindromes.add(input.substring(i - max - 1, max + j + i - 1)); + } + } + } + return palindromes; + } +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java new file mode 100644 index 0000000000..c185dba62b --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.algorithms.factorial; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigInteger; + +import org.junit.Before; +import org.junit.Test; + +public class FactorialUnitTest { + + Factorial factorial; + + @Before + public void setup() { + factorial = new Factorial(); + } + + @Test + public void whenCalculatingFactorialUsingForLoop_thenCorrect() { + int n = 5; + + assertThat(factorial.factorialUsingForLoop(n)).isEqualTo(120); + } + + @Test + public void whenCalculatingFactorialUsingStreams_thenCorrect() { + int n = 5; + + assertThat(factorial.factorialUsingStreams(n)).isEqualTo(120); + } + + @Test + public void whenCalculatingFactorialUsingRecursion_thenCorrect() { + int n = 5; + + assertThat(factorial.factorialUsingRecursion(n)).isEqualTo(120); + } + + @Test + public void whenCalculatingFactorialUsingMemoize_thenCorrect() { + int n = 5; + + assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(120); + + n = 6; + + assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(720); + } + + @Test + public void whenCalculatingFactorialHavingLargeResult_thenCorrect() { + int n = 22; + + assertThat(factorial.factorialHavingLargeResult(n)).isEqualTo(new BigInteger("1124000727777607680000")); + } + + @Test + public void whenCalculatingFactorialUsingApacheCommons_thenCorrect() { + int n = 5; + + assertThat(factorial.factorialUsingApacheCommons(n)).isEqualTo(120); + } + + @Test + public void whenCalculatingFactorialUsingGuava_thenCorrect() { + int n = 22; + + assertThat(factorial.factorialUsingGuava(n)).isEqualTo(new BigInteger("1124000727777607680000")); + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java new file mode 100644 index 0000000000..9f1e6a2519 --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.algorithms.string; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring; +import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce; + +public class LongestSubstringNonRepeatingCharactersUnitTest { + + @Test + void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() { + assertEquals("", getUniqueCharacterSubstringBruteForce("")); + assertEquals("A", getUniqueCharacterSubstringBruteForce("A")); + assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF")); + assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF")); + assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME")); + assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding")); + } + + @Test + void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() { + assertEquals("", getUniqueCharacterSubstring("")); + assertEquals("A", getUniqueCharacterSubstring("A")); + assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF")); + assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF")); + assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME")); + assertEquals("be coding", getUniqueCharacterSubstring("always be coding")); + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java new file mode 100644 index 0000000000..8d225f67fa --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.algorithms.string; + +import static org.junit.Assert.assertEquals; +import java.util.HashSet; +import java.util.Set; +import org.junit.Test; + +public class SubstringPalindromeUnitTest { + + private static final String INPUT_BUBBLE = "bubble"; + private static final String INPUT_CIVIC = "civic"; + private static final String INPUT_INDEED = "indeed"; + private static final String INPUT_ABABAC = "ababac"; + + Set EXPECTED_PALINDROME_BUBBLE = new HashSet() { + { + add("b"); + add("u"); + add("l"); + add("e"); + add("bb"); + add("bub"); + } + }; + + Set EXPECTED_PALINDROME_CIVIC = new HashSet() { + { + add("civic"); + add("ivi"); + add("i"); + add("c"); + add("v"); + } + }; + + Set EXPECTED_PALINDROME_INDEED = new HashSet() { + { + add("i"); + add("n"); + add("d"); + add("e"); + add("ee"); + add("deed"); + } + }; + + Set EXPECTED_PALINDROME_ABABAC = new HashSet() { + { + add("a"); + add("b"); + add("c"); + add("aba"); + add("bab"); + add("ababa"); + } + }; + + private SubstringPalindrome palindrome = new SubstringPalindrome(); + + @Test + public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC)); + } + + @Test + public void whenUsingCenterApproach_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC)); + } + + @Test + public void whenUsingBruteForceApproach_thenFindsAllPalindromes() { + assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE)); + assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED)); + assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC)); + assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC)); + } +} diff --git a/algorithms-miscellaneous-2/README.md b/algorithms-miscellaneous-2/README.md index 6772a94a8d..d693a44f66 100644 --- a/algorithms-miscellaneous-2/README.md +++ b/algorithms-miscellaneous-2/README.md @@ -17,3 +17,4 @@ - [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) - [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings) +- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml index eeae544612..5461f4ebe1 100644 --- a/algorithms-miscellaneous-2/pom.xml +++ b/algorithms-miscellaneous-2/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung algorithms-miscellaneous-2 0.0.1-SNAPSHOT + algorithms-miscellaneous-2 com.baeldung @@ -33,6 +33,11 @@ jgrapht-core ${org.jgrapht.core.version} + + org.jgrapht + jgrapht-ext + ${org.jgrapht.ext.version} + pl.allegro.finance tradukisto @@ -83,6 +88,7 @@ 3.6.1 1.0.1 1.0.1 + 1.0.1 3.9.0 1.11 diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java new file mode 100644 index 0000000000..3b841d574a --- /dev/null +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertTrue; +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; +import org.jgrapht.ext.JGraphXAdapter; +import org.jgrapht.graph.DefaultDirectedGraph; +import org.jgrapht.graph.DefaultEdge; +import org.junit.Before; +import org.junit.Test; +import com.mxgraph.layout.mxCircleLayout; +import com.mxgraph.layout.mxIGraphLayout; +import com.mxgraph.util.mxCellRenderer; + +public class GraphImageGenerationUnitTest { + static DefaultDirectedGraph g; + + @Before + public void createGraph() throws IOException { + File imgFile = new File("src/test/resources/graph.png"); + imgFile.createNewFile(); + g = new DefaultDirectedGraph(DefaultEdge.class); + String x1 = "x1"; + String x2 = "x2"; + String x3 = "x3"; + g.addVertex(x1); + g.addVertex(x2); + g.addVertex(x3); + g.addEdge(x1, x2); + g.addEdge(x2, x3); + g.addEdge(x3, x1); + } + + @Test + public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { + JGraphXAdapter graphAdapter = new JGraphXAdapter(g); + mxIGraphLayout layout = new mxCircleLayout(graphAdapter); + layout.execute(graphAdapter.getDefaultParent()); + File imgFile = new File("src/test/resources/graph.png"); + BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null); + ImageIO.write(image, "PNG", imgFile); + assertTrue(imgFile.exists()); + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png new file mode 100644 index 0000000000..56995b8dd9 Binary files /dev/null and b/algorithms-miscellaneous-2/src/test/resources/graph.png differ diff --git a/algorithms-sorting/pom.xml b/algorithms-sorting/pom.xml index 60ae37f2a4..2aee6e9199 100644 --- a/algorithms-sorting/pom.xml +++ b/algorithms-sorting/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung algorithms-sorting 0.0.1-SNAPSHOT + algorithms-sorting com.baeldung diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java index 0deb48b6a0..945b4ffd7e 100644 --- a/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java @@ -34,7 +34,7 @@ public class MergeSort { while (i < left && j < right) { - if (l[i] < r[j]) + if (l[i] <= r[j]) a[k++] = l[i++]; else a[k++] = r[j++]; diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml index 8e53334521..d9aca6040d 100644 --- a/annotations/annotation-processing/pom.xml +++ b/annotations/annotation-processing/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 annotation-processing - + annotation-processing + com.baeldung 1.0.0-SNAPSHOT diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml index 07ea9a5b5a..422cc7f119 100644 --- a/annotations/annotation-user/pom.xml +++ b/annotations/annotation-user/pom.xml @@ -3,6 +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 annotation-user + annotation-user annotations diff --git a/annotations/pom.xml b/annotations/pom.xml index 2c73d3d91b..6d83f5b057 100644 --- a/annotations/pom.xml +++ b/annotations/pom.xml @@ -4,7 +4,8 @@ 4.0.0 annotations pom - + annotations + parent-modules com.baeldung diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index ddf5844271..18f9c34d64 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -3,10 +3,9 @@ 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 - com.baeldung apache-avro 0.0.1-SNAPSHOT - Apache Avro + apache-avro UTF-8 diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml index 5ddb1ecb59..786f587fb1 100644 --- a/apache-bval/pom.xml +++ b/apache-bval/pom.xml @@ -4,7 +4,8 @@ apache-bval apache-bval 0.0.1-SNAPSHOT - + apache-bval + com.baeldung parent-modules diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml index ac10811e7a..e6be32277d 100644 --- a/apache-curator/pom.xml +++ b/apache-curator/pom.xml @@ -4,6 +4,7 @@ apache-curator 0.0.1-SNAPSHOT jar + apache-curator com.baeldung @@ -58,7 +59,7 @@ 4.0.1 3.4.11 - 2.9.4 + 2.9.7 3.6.1 1.7.0 diff --git a/apache-cxf/cxf-aegis/pom.xml b/apache-cxf/cxf-aegis/pom.xml index b7e9e426a2..1d36178b82 100644 --- a/apache-cxf/cxf-aegis/pom.xml +++ b/apache-cxf/cxf-aegis/pom.xml @@ -2,7 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-aegis - + cxf-aegis + com.baeldung apache-cxf diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml index a9e82c16b3..17f03afd25 100644 --- a/apache-cxf/cxf-introduction/pom.xml +++ b/apache-cxf/cxf-introduction/pom.xml @@ -4,7 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-introduction - + cxf-introduction + com.baeldung apache-cxf diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml index 89acbdf1bd..03d0f67c90 100644 --- a/apache-cxf/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml @@ -4,7 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-jaxrs-implementation - + cxf-jaxrs-implementation + com.baeldung apache-cxf diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml index 31e75e7cdd..97715af54c 100644 --- a/apache-cxf/cxf-spring/pom.xml +++ b/apache-cxf/cxf-spring/pom.xml @@ -3,6 +3,7 @@ 4.0.0 cxf-spring war + cxf-spring com.baeldung diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml index 8918fd4450..0016f33d70 100644 --- a/apache-cxf/pom.xml +++ b/apache-cxf/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung apache-cxf 0.0.1-SNAPSHOT + apache-cxf pom diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml index d4b6c19d03..cb5c96660a 100644 --- a/apache-cxf/sse-jaxrs/pom.xml +++ b/apache-cxf/sse-jaxrs/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 - sse-jaxrs + sse-jaxrs pom diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml index 0f5406fbc7..c7acf22c32 100644 --- a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml @@ -3,15 +3,15 @@ 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 - + sse-jaxrs-client + sse-jaxrs-client + com.baeldung sse-jaxrs 0.0.1-SNAPSHOT - sse-jaxrs-client - 3.2.0 @@ -21,7 +21,6 @@ org.codehaus.mojo exec-maven-plugin - 1.6.0 singleEvent diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml index 2e82dc3829..eeb5726ee1 100644 --- a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml +++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -3,16 +3,16 @@ 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 - + sse-jaxrs-server + sse-jaxrs-server + war + com.baeldung sse-jaxrs 0.0.1-SNAPSHOT - sse-jaxrs-server - war - 2.4.2 false diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml index a3f6604ac4..738accdcb8 100644 --- a/apache-geode/pom.xml +++ b/apache-geode/pom.xml @@ -3,11 +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 - - com.baeldung apache-geode 1.0-SNAPSHOT - + apache-geode + com.baeldung parent-modules diff --git a/apache-opennlp/pom.xml b/apache-opennlp/pom.xml index 985c9a2df2..6b2e6a9729 100644 --- a/apache-opennlp/pom.xml +++ b/apache-opennlp/pom.xml @@ -4,6 +4,7 @@ 4.0.0 apache-opennlp 1.0-SNAPSHOT + apache-opennlp jar diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index a1ec626d43..54c3e8e928 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung apache-poi 0.0.1-SNAPSHOT + apache-poi com.baeldung diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml index da004a7638..a4c09586eb 100644 --- a/apache-pulsar/pom.xml +++ b/apache-pulsar/pom.xml @@ -1,21 +1,22 @@ - 4.0.0 - com.baeldung.pulsar - pulsar-java - 0.0.1 + 4.0.0 + com.baeldung.pulsar + apache-pulsar + 0.0.1 + apache-pulsar - - - org.apache.pulsar - pulsar-client - 2.1.1-incubating - compile - - - - 1.8 - 1.8 - + + + org.apache.pulsar + pulsar-client + 2.1.1-incubating + compile + + + + 1.8 + 1.8 + diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml index 98d9563284..644d70b30a 100644 --- a/apache-shiro/pom.xml +++ b/apache-shiro/pom.xml @@ -5,7 +5,8 @@ 4.0.0 apache-shiro 1.0-SNAPSHOT - + apache-shiro + parent-boot-1 com.baeldung diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml index b22364cb19..ab54fc2cef 100644 --- a/apache-thrift/pom.xml +++ b/apache-thrift/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung apache-thrift 0.0.1-SNAPSHOT + apache-thrift pom diff --git a/apache-tika/pom.xml b/apache-tika/pom.xml index 5a76fdeeda..0399914a5f 100644 --- a/apache-tika/pom.xml +++ b/apache-tika/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung apache-tika 0.0.1-SNAPSHOT - + apache-tika + com.baeldung parent-modules diff --git a/apache-zookeeper/pom.xml b/apache-zookeeper/pom.xml index 0b29186ccc..53e4217358 100644 --- a/apache-zookeeper/pom.xml +++ b/apache-zookeeper/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung apache-zookeeper 0.0.1-SNAPSHOT + apache-zookeeper jar diff --git a/asm/pom.xml b/asm/pom.xml index 5aad2a0e37..e56438c808 100644 --- a/asm/pom.xml +++ b/asm/pom.xml @@ -5,6 +5,7 @@ com.baeldung.examples asm 1.0 + asm jar diff --git a/atomix/pom.xml b/atomix/pom.xml index f85d2d7484..e50c1d867f 100644 --- a/atomix/pom.xml +++ b/atomix/pom.xml @@ -4,7 +4,8 @@ com.atomix.io atomix 0.0.1-SNAPSHOT - + atomix + com.baeldung parent-modules diff --git a/axon/pom.xml b/axon/pom.xml index 915a04feb5..c643ea9e57 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 axon - + axon + parent-modules com.baeldung diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index 9b61aaec3d..98f5f10493 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -3,8 +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 cas-server - war 1.0 + cas-server + war parent-boot-1 diff --git a/cdi/README.md b/cdi/README.md index 0477ce85bd..bfb635be9e 100644 --- a/cdi/README.md +++ b/cdi/README.md @@ -1,3 +1,5 @@ ### Relevant Articles: - [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj) - [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi) +- [Introduction to the Event Notification Model in CDI 2.0](https://www.baeldung.com/cdi-event-notification) + diff --git a/cdi/pom.xml b/cdi/pom.xml index 2c719c1d7f..0cf5062ccc 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - com.baeldung cdi 1.0-SNAPSHOT - + cdi + com.baeldung parent-spring-4 @@ -14,6 +14,16 @@ + + javax.enterprise + cdi-api + ${cdi-api.version} + + + org.jboss.weld.se + weld-se-core + ${weld-se-core.version} + org.hamcrest hamcrest-core @@ -42,11 +52,6 @@ aspectjweaver ${aspectjweaver.version} - - org.jboss.weld.se - weld-se-core - ${weld-se-core.version} - org.springframework spring-test @@ -54,13 +59,13 @@ test - - 1.8.9 - 2.4.1.Final + 2.0.SP1 + 3.0.5.Final + 1.9.2 1.3 3.10.0 4.12 + 5.1.2.RELEASE - diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/application/BootstrappingApplication.java b/cdi/src/main/java/com/baeldung/cdi2observers/application/BootstrappingApplication.java new file mode 100644 index 0000000000..4896408502 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/cdi2observers/application/BootstrappingApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.cdi.cdi2observers.application; + +import com.baeldung.cdi.cdi2observers.events.ExampleEvent; +import javax.enterprise.inject.se.SeContainer; +import javax.enterprise.inject.se.SeContainerInitializer; + +public class BootstrappingApplication { + + public static void main(String... args) { + SeContainerInitializer containerInitializer = SeContainerInitializer.newInstance(); + try (SeContainer container = containerInitializer.initialize()) { + container.getBeanManager().fireEvent(new ExampleEvent("Welcome to Baeldung!")); + } + } +} diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEvent.java b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEvent.java new file mode 100644 index 0000000000..a2329d2ef1 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEvent.java @@ -0,0 +1,14 @@ +package com.baeldung.cdi.cdi2observers.events; + +public class ExampleEvent { + + private final String eventMessage; + + public ExampleEvent(String eventMessage) { + this.eventMessage = eventMessage; + } + + public String getEventMessage() { + return eventMessage; + } +} diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEventSource.java b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEventSource.java new file mode 100644 index 0000000000..f37030778a --- /dev/null +++ b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEventSource.java @@ -0,0 +1,14 @@ +package com.baeldung.cdi.cdi2observers.events; + +import javax.enterprise.event.Event; +import javax.inject.Inject; + +public class ExampleEventSource { + + @Inject + Event exampleEvent; + + public void fireEvent() { + exampleEvent.fireAsync(new ExampleEvent("Welcome to Baeldung!")); + } +} diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/observers/AnotherExampleEventObserver.java b/cdi/src/main/java/com/baeldung/cdi2observers/observers/AnotherExampleEventObserver.java new file mode 100644 index 0000000000..34520c2b3d --- /dev/null +++ b/cdi/src/main/java/com/baeldung/cdi2observers/observers/AnotherExampleEventObserver.java @@ -0,0 +1,12 @@ +package com.baeldung.cdi.cdi2observers.observers; + +import com.baeldung.cdi.cdi2observers.events.ExampleEvent; +import javax.annotation.Priority; +import javax.enterprise.event.Observes; + +public class AnotherExampleEventObserver { + + public String onEvent(@Observes @Priority(2) ExampleEvent event) { + return event.getEventMessage(); + } +} diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/observers/ExampleEventObserver.java b/cdi/src/main/java/com/baeldung/cdi2observers/observers/ExampleEventObserver.java new file mode 100644 index 0000000000..b3522b2ad0 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/cdi2observers/observers/ExampleEventObserver.java @@ -0,0 +1,13 @@ +package com.baeldung.cdi.cdi2observers.observers; + +import com.baeldung.cdi.cdi2observers.events.ExampleEvent; +import com.baeldung.cdi.cdi2observers.services.TextService; +import javax.annotation.Priority; +import javax.enterprise.event.Observes; + +public class ExampleEventObserver { + + public String onEvent(@Observes @Priority(1) ExampleEvent event, TextService textService) { + return textService.parseText(event.getEventMessage()); + } +} diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/services/TextService.java b/cdi/src/main/java/com/baeldung/cdi2observers/services/TextService.java new file mode 100644 index 0000000000..47788a0657 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/cdi2observers/services/TextService.java @@ -0,0 +1,8 @@ +package com.baeldung.cdi.cdi2observers.services; + +public class TextService { + + public String parseText(String text) { + return text.toUpperCase(); + } +} diff --git a/cdi/src/test/java/com/baeldung/test/cdi2observers/tests/TextServiceUnitTest.java b/cdi/src/test/java/com/baeldung/test/cdi2observers/tests/TextServiceUnitTest.java new file mode 100644 index 0000000000..deecf13f9a --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/cdi2observers/tests/TextServiceUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.cdi.cdi2observers.tests; + +import com.baeldung.cdi.cdi2observers.services.TextService; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TextServiceUnitTest { + + @Test + public void givenTextServiceInstance_whenCalledparseText_thenCorrect() { + TextService textService = new TextService(); + assertThat(textService.parseText("Baeldung")).isEqualTo("BAELDUNG"); + } +} diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml index 909250710e..e54c766280 100644 --- a/core-groovy/pom.xml +++ b/core-groovy/pom.xml @@ -4,6 +4,7 @@ 4.0.0 core-groovy 1.0-SNAPSHOT + core-groovy jar diff --git a/core-java-10/README.md b/core-java-10/README.md index 84fa381a26..f0a25712a7 100644 --- a/core-java-10/README.md +++ b/core-java-10/README.md @@ -4,3 +4,4 @@ - [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference) - [Guide to Java 10](http://www.baeldung.com/java-10-overview) - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) +- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler) diff --git a/core-java-11/README.md b/core-java-11/README.md new file mode 100644 index 0000000000..181ada3f45 --- /dev/null +++ b/core-java-11/README.md @@ -0,0 +1,5 @@ +### Relevant articles + +- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code) +- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params) + diff --git a/core-java-11/src/main/java/com/baeldung/Outer.java b/core-java-11/src/main/java/com/baeldung/Outer.java new file mode 100644 index 0000000000..1d3cd72b44 --- /dev/null +++ b/core-java-11/src/main/java/com/baeldung/Outer.java @@ -0,0 +1,24 @@ +package com.baeldung; + +import java.lang.reflect.Method; + +public class Outer { + + public void outerPublic() { + } + + private void outerPrivate() { + } + + class Inner { + + public void innerPublic() { + outerPrivate(); + } + + public void innerPublicReflection(Outer ob) throws Exception { + Method method = ob.getClass().getDeclaredMethod("outerPrivate"); + method.invoke(ob); + } + } +} \ No newline at end of file diff --git a/core-java-11/src/main/java/com/baeldung/add b/core-java-11/src/main/java/com/baeldung/add new file mode 100755 index 0000000000..539c1a43d4 --- /dev/null +++ b/core-java-11/src/main/java/com/baeldung/add @@ -0,0 +1,12 @@ +#!/usr/local/bin/java --source 11 + +import java.util.Arrays; + +public class Addition +{ + public static void main(String[] args) { + System.out.println(Arrays.stream(args) + .mapToInt(Integer::parseInt) + .sum()); + } +} \ No newline at end of file diff --git a/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java b/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java new file mode 100644 index 0000000000..43e9022a64 --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung; + +import static org.hamcrest.CoreMatchers.is; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class NewStringAPIUnitTest { + + @Test + public void whenRepeatStringTwice_thenGetStringTwice() { + String output = "La ".repeat(2) + "Land"; + + is(output).equals("La La Land"); + } + + @Test + public void whenStripString_thenReturnStringWithoutWhitespaces() { + is("\n\t hello \u2005".strip()).equals("hello"); + } + + @Test + public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() { + is("\n\t hello \u2005".trim()).equals("hello \u2005"); + } + + @Test + public void whenBlankString_thenReturnTrue() { + assertTrue("\n\t\u2005 ".isBlank()); + } + + @Test + public void whenMultilineString_thenReturnNonEmptyLineCount() { + String multilineStr = "This is\n \n a multiline\n string."; + + long lineCount = multilineStr.lines() + .filter(String::isBlank) + .count(); + + is(lineCount).equals(3L); + } +} \ No newline at end of file diff --git a/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java b/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java new file mode 100644 index 0000000000..9e6bd72680 --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung; + +import static org.junit.Assert.assertTrue; +import static org.hamcrest.CoreMatchers.is; + +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.Test; + +public class OuterUnitTest { + + private static final String NEST_HOST_NAME = "com.baeldung.Outer"; + + @Test + public void whenGetNestHostFromOuter_thenGetNestHost() { + is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME); + } + + @Test + public void whenGetNestHostFromInner_thenGetNestHost() { + is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME); + } + + @Test + public void whenCheckNestmatesForNestedClasses_thenGetTrue() { + is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true); + } + + @Test + public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() { + is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false); + } + + @Test + public void whenGetNestMembersForNestedClasses_thenGetAllNestedClasses() { + Set nestMembers = Arrays.stream(Outer.Inner.class.getNestMembers()) + .map(Class::getName) + .collect(Collectors.toSet()); + + is(nestMembers.size()).equals(2); + + assertTrue(nestMembers.contains("com.baeldung.Outer")); + assertTrue(nestMembers.contains("com.baeldung.Outer$Inner")); + } +} \ No newline at end of file diff --git a/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java new file mode 100644 index 0000000000..281155138d --- /dev/null +++ b/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.optional; + +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link Optional} in Java 11. + */ +public class OptionalUnitTest { + + @Test + public void givenAnEmptyOptional_isEmpty_thenBehavesAsExpected() { + Optional opt = Optional.of("Baeldung"); + assertFalse(opt.isEmpty()); + + opt = Optional.ofNullable(null); + assertTrue(opt.isEmpty()); + } +} diff --git a/core-java-8/README.md b/core-java-8/README.md index ffd629a170..f9af585ab3 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -15,7 +15,6 @@ - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) - [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java) -- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) @@ -33,3 +32,8 @@ - [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) - [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) - [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) +- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements) +- [Java @Override Annotation](https://www.baeldung.com/java-override) +- [Java @SuppressWarnings Annotation](https://www.baeldung.com/java-suppresswarnings) +- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs) +- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 18bdaa15f4..112e8b764d 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung core-java-8 @@ -104,6 +104,24 @@ aspectjweaver ${asspectj.version} + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + org.jmockit + jmockit + ${jmockit.version} + test + @@ -119,7 +137,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.1 + ${maven-compiler-plugin.version} 1.8 1.8 @@ -142,6 +160,16 @@ + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar + + true + + @@ -159,9 +187,14 @@ 3.6.1 1.8.9 + 2.0.0-RC.4 + 1.44 1.7.0 1.19 1.19 2.0.4.RELEASE + + 3.8.0 + 2.22.1 diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/Electronic.java b/core-java-8/src/main/java/com/baeldung/interfaces/Electronic.java new file mode 100644 index 0000000000..bfbc381483 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/Electronic.java @@ -0,0 +1,22 @@ +package com.baeldung.interfaces; + +public interface Electronic { + //Constant variable + public static final String LED = "LED"; + + //Abstract method + public int getElectricityUse(); + + // Static method + public static boolean isEnergyEfficient(String electtronicType) { + if (electtronicType.equals(LED)) { + return true; + } + return false; + } + + //Default method + public default void printDescription() { + System.out.println("Electronic Description"); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/Employee.java b/core-java-8/src/main/java/com/baeldung/interfaces/Employee.java new file mode 100644 index 0000000000..903bc81e6f --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/Employee.java @@ -0,0 +1,15 @@ +package com.baeldung.interfaces; + +public class Employee { + + private double salary; + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java b/core-java-8/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java new file mode 100644 index 0000000000..cfa4226c1a --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java @@ -0,0 +1,18 @@ +package com.baeldung.interfaces; + +import java.util.Comparator; + +public class EmployeeSalaryComparator implements Comparator { + + @Override + public int compare(Employee employeeA, Employee employeeB) { + + if(employeeA.getSalary() < employeeB.getSalary()){ + return -1; + }else if(employeeA.getSalary() > employeeB.getSalary()){ + return 1; + }else{ + return 0; + } + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/HasColor.java b/core-java-8/src/main/java/com/baeldung/interfaces/HasColor.java new file mode 100644 index 0000000000..6eface2d47 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/HasColor.java @@ -0,0 +1,5 @@ +package com.baeldung.interfaces; + +public interface HasColor { + public String getColor(); +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/Motorcycle.java b/core-java-8/src/main/java/com/baeldung/interfaces/Motorcycle.java new file mode 100644 index 0000000000..6003f476a3 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/Motorcycle.java @@ -0,0 +1,10 @@ +package com.baeldung.interfaces; + +import com.baeldung.interfaces.multiinheritance.Transform; + +public class Motorcycle implements Transform { + @Override + public void transform() { + // Implementation + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/Truck.java b/core-java-8/src/main/java/com/baeldung/interfaces/Truck.java new file mode 100644 index 0000000000..d78de23371 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/Truck.java @@ -0,0 +1,8 @@ +package com.baeldung.interfaces; + +public class Truck extends Vehicle { + @Override + public void transform() { + // implementation + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/Vehicle.java b/core-java-8/src/main/java/com/baeldung/interfaces/Vehicle.java new file mode 100644 index 0000000000..8b4662e1a3 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/Vehicle.java @@ -0,0 +1,6 @@ +package com.baeldung.interfaces; + +import com.baeldung.interfaces.multiinheritance.Transform; + +public abstract class Vehicle implements Transform { +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java new file mode 100644 index 0000000000..b951fc0273 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java @@ -0,0 +1,13 @@ +package com.baeldung.interfaces.multiinheritance; + +public class Car implements Fly, Transform { + @Override + public void fly() { + System.out.println("I can Fly!!"); + } + + @Override + public void transform() { + System.out.println("I can Transform!!"); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java new file mode 100644 index 0000000000..d84182aec6 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java @@ -0,0 +1,5 @@ +package com.baeldung.interfaces.multiinheritance; + +public abstract interface Fly{ + void fly(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java new file mode 100644 index 0000000000..8bdba43a05 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java @@ -0,0 +1,10 @@ +package com.baeldung.interfaces.multiinheritance; + +public interface Transform { + + void transform(); + + default void printSpecs(){ + System.out.println("Transform Specification"); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java new file mode 100644 index 0000000000..fb0d36e3e0 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java @@ -0,0 +1,13 @@ +package com.baeldung.interfaces.multiinheritance; + +public class Vehicle implements Fly, Transform { + @Override + public void fly() { + System.out.println("I can Fly!!"); + } + + @Override + public void transform() { + System.out.println("I can Transform!!"); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java new file mode 100644 index 0000000000..afb3142d96 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java @@ -0,0 +1,25 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Circle implements Shape { + + private double radius; + + public Circle(double radius){ + this.radius = radius; + } + + @Override + public String name() { + return "Circle"; + } + + @Override + public double area() { + return Math.PI * (radius * radius); + } + + @Override + public String getColor() { + return "green"; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java new file mode 100644 index 0000000000..d9c9dd107a --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java @@ -0,0 +1,26 @@ +package com.baeldung.interfaces.polymorphysim; + +import java.util.ArrayList; + +public class DisplayShape { + + private ArrayList shapes; + + public ArrayList getShapes() { + return shapes; + } + + public DisplayShape() { + shapes = new ArrayList<>(); + } + + public void add(Shape shape) { + shapes.add(shape); + } + + public void display() { + for (Shape shape : shapes) { + System.out.println(shape.name() + " area: " + shape.area()); + } + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/FunctionalMain.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/FunctionalMain.java new file mode 100644 index 0000000000..5316dd7db7 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/FunctionalMain.java @@ -0,0 +1,23 @@ +package com.baeldung.interfaces.polymorphysim; + +import java.util.function.Predicate; + +public class FunctionalMain { + +public static void main(String[] args) { + Shape circleShape = new Circle(2); + Shape squareShape = new Square(2); + + DisplayShape DisplayShape = new DisplayShape(); + DisplayShape.add(circleShape); + DisplayShape.add(squareShape); + + Predicate checkArea = (shape) -> shape.area() < 5; + + for (Shape shape : DisplayShape.getShapes()) { + if (checkArea.test(shape)) { + System.out.println(shape.name() + " " + shape.area()); + } + } +} +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java new file mode 100644 index 0000000000..cc43c1300b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java @@ -0,0 +1,15 @@ +package com.baeldung.interfaces.polymorphysim; + +public class MainPolymorphic { + public static void main(String[] args){ + + Shape circleShape = new Circle(2); + Shape squareShape = new Square(2); + + DisplayShape displayShape = new DisplayShape(); + displayShape.add(circleShape); + displayShape.add(squareShape); + + displayShape.display(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java new file mode 100644 index 0000000000..560e07a80a --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java @@ -0,0 +1,9 @@ +package com.baeldung.interfaces.polymorphysim; + +import com.baeldung.interfaces.HasColor; + +public interface Shape extends HasColor { + + public abstract String name(); + public abstract double area(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java new file mode 100644 index 0000000000..00b75ace20 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java @@ -0,0 +1,25 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Square implements Shape { + + private double width; + + public Square(double width) { + this.width = width; + } + + @Override + public String name() { + return "Square"; + } + + @Override + public double area() { + return width * width; + } + + @Override + public String getColor() { + return "red"; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java b/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java new file mode 100644 index 0000000000..7ded5e6621 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.interfaces; + +import com.baeldung.interfaces.polymorphysim.Circle; +import com.baeldung.interfaces.polymorphysim.Shape; +import com.baeldung.interfaces.polymorphysim.Square; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +public class PolymorphysimUnitTest { + + @Test + public void whenInterfacePointsToCircle_CircleAreaMethodisBeingCalled(){ + double expectedArea = 12.566370614359172; + Shape circle = new Circle(2); + double actualArea = circle.area(); + Assertions.assertThat(actualArea).isEqualTo(expectedArea); + } + + @Test + public void whenInterfacePointsToSquare_SquareAreaMethodisBeingCalled(){ + double expectedArea = 4; + Shape square = new Square(2); + double actualArea = square.area(); + Assertions.assertThat(actualArea).isEqualTo(expectedArea); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8PredicateChainUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8PredicateChainUnitTest.java new file mode 100644 index 0000000000..fa579f9a00 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8PredicateChainUnitTest.java @@ -0,0 +1,131 @@ +package com.baeldung.java8; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class Java8PredicateChainUnitTest { + + private List names = Arrays.asList("Adam", "Alexander", "John", "Tom"); + + @Test + public void whenFilterList_thenSuccess() { + List result = names.stream() + .filter(name -> name.startsWith("A")) + .collect(Collectors.toList()); + + assertEquals(2, result.size()); + assertThat(result, contains("Adam", "Alexander")); + } + + @Test + public void whenFilterListWithMultipleFilters_thenSuccess() { + List result = names.stream() + .filter(name -> name.startsWith("A")) + .filter(name -> name.length() < 5) + .collect(Collectors.toList()); + + assertEquals(1, result.size()); + assertThat(result, contains("Adam")); + } + + @Test + public void whenFilterListWithComplexPredicate_thenSuccess() { + List result = names.stream() + .filter(name -> name.startsWith("A") && name.length() < 5) + .collect(Collectors.toList()); + + assertEquals(1, result.size()); + assertThat(result, contains("Adam")); + } + + @Test + public void whenFilterListWithCombinedPredicatesInline_thenSuccess() { + List result = names.stream() + .filter(((Predicate) name -> name.startsWith("A")).and(name -> name.length() < 5)) + .collect(Collectors.toList()); + + assertEquals(1, result.size()); + assertThat(result, contains("Adam")); + } + + @Test + public void whenFilterListWithCombinedPredicatesUsingAnd_thenSuccess() { + Predicate predicate1 = str -> str.startsWith("A"); + Predicate predicate2 = str -> str.length() < 5; + + List result = names.stream() + .filter(predicate1.and(predicate2)) + .collect(Collectors.toList()); + + assertEquals(1, result.size()); + assertThat(result, contains("Adam")); + } + + @Test + public void whenFilterListWithCombinedPredicatesUsingOr_thenSuccess() { + Predicate predicate1 = str -> str.startsWith("J"); + Predicate predicate2 = str -> str.length() < 4; + + List result = names.stream() + .filter(predicate1.or(predicate2)) + .collect(Collectors.toList()); + + assertEquals(2, result.size()); + assertThat(result, contains("John", "Tom")); + } + + @Test + public void whenFilterListWithCombinedPredicatesUsingOrAndNegate_thenSuccess() { + Predicate predicate1 = str -> str.startsWith("J"); + Predicate predicate2 = str -> str.length() < 4; + + List result = names.stream() + .filter(predicate1.or(predicate2.negate())) + .collect(Collectors.toList()); + + assertEquals(3, result.size()); + assertThat(result, contains("Adam", "Alexander", "John")); + } + + @Test + public void whenFilterListWithCollectionOfPredicatesUsingAnd_thenSuccess() { + List> allPredicates = new ArrayList>(); + allPredicates.add(str -> str.startsWith("A")); + allPredicates.add(str -> str.contains("d")); + allPredicates.add(str -> str.length() > 4); + + List result = names.stream() + .filter(allPredicates.stream() + .reduce(x -> true, Predicate::and)) + .collect(Collectors.toList()); + + assertEquals(1, result.size()); + assertThat(result, contains("Alexander")); + } + + @Test + public void whenFilterListWithCollectionOfPredicatesUsingOr_thenSuccess() { + List> allPredicates = new ArrayList>(); + allPredicates.add(str -> str.startsWith("A")); + allPredicates.add(str -> str.contains("d")); + allPredicates.add(str -> str.length() > 4); + + List result = names.stream() + .filter(allPredicates.stream() + .reduce(x -> false, Predicate::or)) + .collect(Collectors.toList()); + + assertEquals(2, result.size()); + assertThat(result, contains("Adam", "Alexander")); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java new file mode 100644 index 0000000000..04c1a0b74e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.time; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ LocalDateTime.class }) +public class LocalDateTimeUnitTest { + + @Test + public void givenLocalDateTimeMock_whenNow_thenGetFixedLocalDateTime() { + Clock clock = Clock.fixed(Instant.parse("2014-12-22T10:15:30.00Z"), ZoneId.of("UTC")); + LocalDateTime dateTime = LocalDateTime.now(clock); + mockStatic(LocalDateTime.class); + when(LocalDateTime.now()).thenReturn(dateTime); + String dateTimeExpected = "2014-12-22T10:15:30"; + + LocalDateTime now = LocalDateTime.now(); + + assertThat(now).isEqualTo(dateTimeExpected); + } + + @Test + public void givenFixedClock_whenNow_thenGetFixedLocalDateTime() { + Clock clock = Clock.fixed(Instant.parse("2014-12-22T10:15:30.00Z"), ZoneId.of("UTC")); + String dateTimeExpected = "2014-12-22T10:15:30"; + + LocalDateTime dateTime = LocalDateTime.now(clock); + + assertThat(dateTime).isEqualTo(dateTimeExpected); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java b/core-java-8/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java new file mode 100644 index 0000000000..13861dfd0b --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.time; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; + +import static org.assertj.core.api.Assertions.assertThat; + +public class LocalDateTimeWithJMockUnitTest { + + @Test + public void givenLocalDateTimeWithJMock_whenNow_thenGetFixedLocalDateTime() { + Clock clock = Clock.fixed(Instant.parse("2014-12-21T10:15:30.00Z"), ZoneId.of("UTC")); + new MockUp() { + @Mock + public LocalDateTime now() { + return LocalDateTime.now(clock); + } + }; + String dateTimeExpected = "2014-12-21T10:15:30"; + + LocalDateTime now = LocalDateTime.now(); + + assertThat(now).isEqualTo(dateTimeExpected); + } + + @Test + public void givenLocalDateTimeWithExpectations_whenNow_thenGetFixedLocalDateTime() { + Clock clock = Clock.fixed(Instant.parse("2014-12-23T10:15:30.00Z"), ZoneId.of("UTC")); + LocalDateTime dateTimeExpected = LocalDateTime.now(clock); + new Expectations(LocalDateTime.class) { + { + LocalDateTime.now(); + result = dateTimeExpected; + } + }; + + LocalDateTime now = LocalDateTime.now(); + + assertThat(now).isEqualTo(dateTimeExpected); + } +} diff --git a/core-java-9/README.md b/core-java-9/README.md index 38816471aa..c96267dc95 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -9,7 +9,6 @@ - [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods) - [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) - [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture) -- [Spring Security – Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login) - [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) - [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api) - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index f22d0a3ed9..cd1fa74dbb 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung core-java-9 0.2-SNAPSHOT core-java-9 diff --git a/core-java-arrays/README.md b/core-java-arrays/README.md index bda2cf90bf..56110585ac 100644 --- a/core-java-arrays/README.md +++ b/core-java-arrays/README.md @@ -12,4 +12,4 @@ - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array) - [Array Operations in Java](http://www.baeldung.com/java-common-array-operations) - +- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) diff --git a/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java b/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java index 757a8f8ec1..a7592574d9 100644 --- a/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java +++ b/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java @@ -7,6 +7,14 @@ public class Employee implements Serializable { private int id; private String name; + public Employee() { + } + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + public int getId() { return id; } diff --git a/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java b/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java new file mode 100644 index 0000000000..59035738fe --- /dev/null +++ b/core-java-arrays/src/test/java/com/baeldung/sort/ArraySortUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.sort; + +import com.baeldung.arraycopy.model.Employee; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertArrayEquals; + +public class ArraySortUnitTest { + private Employee[] employees; + private int[] numbers; + private String[] strings; + + private Employee john = new Employee(6, "John"); + private Employee mary = new Employee(3, "Mary"); + private Employee david = new Employee(4, "David"); + + @Before + public void setup() { + createEmployeesArray(); + createNumbersArray(); + createStringArray(); + } + + private void createEmployeesArray() { + employees = new Employee[]{john, mary, david}; + } + + private void createNumbersArray() { + numbers = new int[]{-8, 7, 5, 9, 10, -2, 3}; + } + + private void createStringArray() { + strings = new String[]{"learning", "java", "with", "baeldung"}; + } + + @Test + public void givenIntArray_whenSortingAscending_thenCorrectlySorted() { + Arrays.sort(numbers); + + assertArrayEquals(new int[]{-8, -2, 3, 5, 7, 9, 10}, numbers); + } + + @Test + public void givenIntArray_whenSortingDescending_thenCorrectlySorted() { + numbers = IntStream.of(numbers).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray(); + + assertArrayEquals(new int[]{10, 9, 7, 5, 3, -2, -8}, numbers); + } + + @Test + public void givenStringArray_whenSortingAscending_thenCorrectlySorted() { + Arrays.sort(strings); + + assertArrayEquals(new String[]{"baeldung", "java", "learning", "with"}, strings); + } + + @Test + public void givenStringArray_whenSortingDescending_thenCorrectlySorted() { + Arrays.sort(strings, Comparator.reverseOrder()); + + assertArrayEquals(new String[]{"with", "learning", "java", "baeldung"}, strings); + } + + @Test + public void givenObjectArray_whenSortingAscending_thenCorrectlySorted() { + Arrays.sort(employees, Comparator.comparing(Employee::getName)); + + assertArrayEquals(new Employee[]{david, john, mary}, employees); + } + + @Test + public void givenObjectArray_whenSortingDescending_thenCorrectlySorted() { + Arrays.sort(employees, Comparator.comparing(Employee::getName).reversed()); + + assertArrayEquals(new Employee[]{mary, john, david}, employees); + } + + @Test + public void givenObjectArray_whenSortingMultipleAttributesAscending_thenCorrectlySorted() { + Arrays.sort(employees, Comparator.comparing(Employee::getName).thenComparing(Employee::getId)); + + assertArrayEquals(new Employee[]{david, john, mary}, employees); + } + +} diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md new file mode 100644 index 0000000000..aba53f5b30 --- /dev/null +++ b/core-java-collections-list/README.md @@ -0,0 +1,27 @@ +========= + +## Core Java Collections List Cookbooks and Examples + +### Relevant Articles: +- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list) +- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) +- [Random List Element](http://www.baeldung.com/java-random-list-element) +- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list) +- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list) +- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) +- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) +- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list) +- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list) +- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) +- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) +- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) +- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) +- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list) +- [Check If Two Lists are Equal in Java](http://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) +- [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) +- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist) +- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) \ No newline at end of file diff --git a/core-java-collections-list/pom.xml b/core-java-collections-list/pom.xml new file mode 100644 index 0000000000..ee99e470d0 --- /dev/null +++ b/core-java-collections-list/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + core-java-collections-list + 0.1.0-SNAPSHOT + jar + core-java-collections-list + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + 4.1 + 3.8.1 + 1.7.0 + 3.11.1 + 1.16.12 + + diff --git a/core-java-collections/src/main/java/com/baeldung/classcastexception/ClassCastException.java b/core-java-collections-list/src/main/java/com/baeldung/classcastexception/ClassCastException.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/classcastexception/ClassCastException.java rename to core-java-collections-list/src/main/java/com/baeldung/classcastexception/ClassCastException.java diff --git a/core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java b/core-java-collections-list/src/main/java/com/baeldung/findanelement/Customer.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java rename to core-java-collections-list/src/main/java/com/baeldung/findanelement/Customer.java diff --git a/core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java b/core-java-collections-list/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java rename to core-java-collections-list/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java b/core-java-collections-list/src/main/java/com/baeldung/java/list/CopyListService.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java rename to core-java-collections-list/src/main/java/com/baeldung/java/list/CopyListService.java diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/CustomList.java b/core-java-collections-list/src/main/java/com/baeldung/java/list/CustomList.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/java/list/CustomList.java rename to core-java-collections-list/src/main/java/com/baeldung/java/list/CustomList.java diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java b/core-java-collections-list/src/main/java/com/baeldung/java/list/Flower.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/java/list/Flower.java rename to core-java-collections-list/src/main/java/com/baeldung/java/list/Flower.java diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/ReverseIterator.java b/core-java-collections-list/src/main/java/com/baeldung/java/list/ReverseIterator.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/java/list/ReverseIterator.java rename to core-java-collections-list/src/main/java/com/baeldung/java/list/ReverseIterator.java diff --git a/core-java-collections-list/src/main/java/com/baeldung/java/list/WaysToIterate.java b/core-java-collections-list/src/main/java/com/baeldung/java/list/WaysToIterate.java new file mode 100644 index 0000000000..3cce08eabb --- /dev/null +++ b/core-java-collections-list/src/main/java/com/baeldung/java/list/WaysToIterate.java @@ -0,0 +1,67 @@ +package com.baeldung.java.list; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +/** + * Demonstrates the different ways to loop over + * the elements of a list. + */ +public class WaysToIterate { + + List countries = Arrays.asList("Germany", "Panama", "Australia"); + + /** + * Iterate over a list using a basic for loop + */ + public void iterateWithForLoop() { + for (int i = 0; i < countries.size(); i++) { + System.out.println(countries.get(i)); + } + } + + /** + * Iterate over a list using the enhanced for loop + */ + public void iterateWithEnhancedForLoop() { + for (String country : countries) { + System.out.println(country); + } + } + + /** + * Iterate over a list using an Iterator + */ + public void iterateWithIterator() { + Iterator countriesIterator = countries.iterator(); + while(countriesIterator.hasNext()) { + System.out.println(countriesIterator.next()); + } + } + + /** + * Iterate over a list using a ListIterator + */ + public void iterateWithListIterator() { + ListIterator listIterator = countries.listIterator(); + while(listIterator.hasNext()) { + System.out.println(listIterator.next()); + } + } + + /** + * Iterate over a list using the Iterable.forEach() method + */ + public void iterateWithForEach() { + countries.forEach(System.out::println); + } + + /** + * Iterate over a list using the Stream.forEach() method + */ + public void iterateWithStreamForEach() { + countries.stream().forEach((c) -> System.out.println(c)); + } +} \ No newline at end of file diff --git a/core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Car.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java rename to core-java-collections-list/src/main/java/com/baeldung/java_8_features/Car.java diff --git a/core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java b/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Person.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java rename to core-java-collections-list/src/main/java/com/baeldung/java_8_features/Person.java diff --git a/core-java-8/src/main/java/com/baeldung/list/Flower.java b/core-java-collections-list/src/main/java/com/baeldung/list/Flower.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/list/Flower.java rename to core-java-collections-list/src/main/java/com/baeldung/list/Flower.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/listoflist/Pen.java b/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pen.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/listoflist/Pen.java rename to core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pen.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/listoflist/Pencil.java b/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pencil.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/listoflist/Pencil.java rename to core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pencil.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/listoflist/Rubber.java b/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Rubber.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/listoflist/Rubber.java rename to core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Rubber.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/listoflist/Stationery.java b/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Stationery.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/listoflist/Stationery.java rename to core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Stationery.java diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java b/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java new file mode 100644 index 0000000000..e11f8e8ba0 --- /dev/null +++ b/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java @@ -0,0 +1,36 @@ +package com.baeldung.list.multidimensional; + +import java.util.ArrayList; + +public class ArrayListOfArrayList { + + public static void main(String args[]) { + + int vertexCount = 3; + ArrayList> graph = new ArrayList<>(vertexCount); + + //Initializing each element of ArrayList with ArrayList + for(int i = 0; i< vertexCount; i++) { + graph.add(new ArrayList()); + } + + //We can add any number of columns to each row + graph.get(0).add(1); + graph.get(1).add(2); + graph.get(2).add(0); + graph.get(1).add(0); + graph.get(2).add(1); + graph.get(0).add(2); + + vertexCount = graph.size(); + for(int i = 0; i < vertexCount; i++) { + int edgeCount = graph.get(i).size(); + for(int j = 0; j < edgeCount; j++) { + Integer startVertex = i; + Integer endVertex = graph.get(i).get(j); + System.out.printf("Vertex %d is connected to vertex %d%n", startVertex, endVertex); + } + } + } + +} \ No newline at end of file diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ThreeDimensionalArrayList.java b/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ThreeDimensionalArrayList.java new file mode 100644 index 0000000000..2021afb0ee --- /dev/null +++ b/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ThreeDimensionalArrayList.java @@ -0,0 +1,45 @@ +package com.baeldung.list.multidimensional; + +import java.util.ArrayList; + +public class ThreeDimensionalArrayList { + + public static void main(String args[]) { + + int x_axis_length = 2; + int y_axis_length = 2; + int z_axis_length = 2; + ArrayList< ArrayList< ArrayList > > space = new ArrayList<>(x_axis_length); + + //Initializing each element of ArrayList with ArrayList< ArrayList > + for(int i = 0; i < x_axis_length; i++) { + space.add(new ArrayList< ArrayList >(y_axis_length)); + for(int j = 0; j < y_axis_length; j++) { + space.get(i).add(new ArrayList(z_axis_length)); + } + } + + //Set Red color for points (0,0,0) and (0,0,1) + space.get(0).get(0).add(0,"Red"); + space.get(0).get(0).add(1,"Red"); + //Set Blue color for points (0,1,0) and (0,1,1) + space.get(0).get(1).add(0,"Blue"); + space.get(0).get(1).add(1,"Blue"); + //Set Green color for points (1,0,0) and (1,0,1) + space.get(1).get(0).add(0,"Green"); + space.get(1).get(0).add(1,"Green"); + //Set Yellow color for points (1,1,0) and (1,1,1) + space.get(1).get(1).add(0,"Yellow"); + space.get(1).get(1).add(1,"Yellow"); + + //Printing colors for all the points + for(int i = 0; i < x_axis_length; i++) { + for(int j = 0; j < y_axis_length; j++) { + for(int k = 0; k < z_axis_length; k++) { + System.out.println("Color of point ("+i+","+j+","+k+") is :"+space.get(i).get(j).get(k)); + } + } + } + } + +} \ No newline at end of file diff --git a/core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java b/core-java-collections-list/src/main/java/com/baeldung/list/removeall/RemoveAll.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java rename to core-java-collections-list/src/main/java/com/baeldung/list/removeall/RemoveAll.java diff --git a/ethereumj/src/main/resources/logback.xml b/core-java-collections-list/src/main/resources/logback.xml similarity index 100% rename from ethereumj/src/main/resources/logback.xml rename to core-java-collections-list/src/main/resources/logback.xml diff --git a/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/collection/ClearVsRemoveAllUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java b/core-java-collections-list/src/test/java/com/baeldung/collection/CollectionsEmpty.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java rename to core-java-collections-list/src/test/java/com/baeldung/collection/CollectionsEmpty.java diff --git a/core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/java/list/CustomListUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java/list/CustomListUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/java/list/CustomListUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/java/list/CustomListUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java diff --git a/core-java-collections-list/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java new file mode 100644 index 0000000000..973c60b233 --- /dev/null +++ b/core-java-collections-list/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.java.list; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +import org.junit.Test; + +public class WaysToIterateUnitTest { + + List globalCountries = new ArrayList(); + List europeanCountries = Arrays.asList("Germany", "Panama", "Australia"); + + @Test + public void whenIteratingUsingForLoop_thenReturnThreeAsSizeOfList() { + for (int i = 0; i < europeanCountries.size(); i++) { + globalCountries.add(europeanCountries.get(i)); + } + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingEnhancedForLoop_thenReturnThreeAsSizeOfList() { + for (String country : europeanCountries) { + globalCountries.add(country); + } + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingIterator_thenReturnThreeAsSizeOfList() { + Iterator countriesIterator = europeanCountries.iterator(); + while (countriesIterator.hasNext()) { + globalCountries.add(countriesIterator.next()); + } + + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingListIterator_thenReturnThreeAsSizeOfList() { + ListIterator countriesIterator = europeanCountries.listIterator(); + while (countriesIterator.hasNext()) { + globalCountries.add(countriesIterator.next()); + } + + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingForEach_thenReturnThreeAsSizeOfList() { + europeanCountries.forEach(country -> globalCountries.add(country)); + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingStreamForEach_thenReturnThreeAsSizeOfList() { + europeanCountries.stream().forEach((country) -> globalCountries.add(country)); + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } +} \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/list/AddElementsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/list/AddElementsUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java b/core-java-collections-list/src/test/java/org/baeldung/RandomListElementUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java rename to core-java-collections-list/src/test/java/org/baeldung/RandomListElementUnitTest.java index 6ae7c40f4d..4f5ba0f82f 100644 --- a/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java +++ b/core-java-collections-list/src/test/java/org/baeldung/RandomListElementUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package org.baeldung; import com.google.common.collect.Lists; import org.junit.Test; diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java b/core-java-collections-list/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java rename to core-java-collections-list/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java b/core-java-collections-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java rename to core-java-collections-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java b/core-java-collections-list/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java rename to core-java-collections-list/src/test/java/org/baeldung/java/collections/JavaCollectionCleanupUnitTest.java diff --git a/core-java-collections/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java b/core-java-collections-list/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java rename to core-java-collections-list/src/test/java/org/baeldung/java/lists/ListAssertJUnitTest.java diff --git a/core-java-collections-list/src/test/java/org/baeldung/java/lists/ListJUnitTest.java b/core-java-collections-list/src/test/java/org/baeldung/java/lists/ListJUnitTest.java new file mode 100644 index 0000000000..f9c9d3fda8 --- /dev/null +++ b/core-java-collections-list/src/test/java/org/baeldung/java/lists/ListJUnitTest.java @@ -0,0 +1,47 @@ +package org.baeldung.java.lists; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.HashSet; + +import java.util.stream.Collectors; + +public class ListJUnitTest { + + private final List list1 = Arrays.asList("1", "2", "3", "4"); + private final List list2 = Arrays.asList("1", "2", "3", "4"); + private final List list3 = Arrays.asList("1", "2", "4", "3"); + + @Test + public void whenTestingForEquality_ShouldBeEqual() throws Exception { + Assert.assertEquals(list1, list2); + Assert.assertNotSame(list1, list2); + Assert.assertNotEquals(list1, list3); + } + + @Test + public void whenIntersection_ShouldReturnCommonElements() throws Exception { + List list = Arrays.asList("red", "blue", "blue", "green", "red"); + List otherList = Arrays.asList("red", "green", "green", "yellow"); + + Set commonElements = new HashSet(Arrays.asList("red", "green")); + + Set result = list.stream() + .distinct() + .filter(otherList::contains) + .collect(Collectors.toSet()); + + Assert.assertEquals(commonElements, result); + + Set inverseResult = otherList.stream() + .distinct() + .filter(list::contains) + .collect(Collectors.toSet()); + + Assert.assertEquals(commonElements, inverseResult); + } +} diff --git a/core-java-collections/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java b/core-java-collections-list/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java rename to core-java-collections-list/src/test/java/org/baeldung/java/lists/ListTestNgUnitTest.java diff --git a/core-java-collections/src/test/java/org/baeldung/java/lists/README.md b/core-java-collections-list/src/test/java/org/baeldung/java/lists/README.md similarity index 100% rename from core-java-collections/src/test/java/org/baeldung/java/lists/README.md rename to core-java-collections-list/src/test/java/org/baeldung/java/lists/README.md diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 0fcf7367c7..1a90d01a82 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -3,36 +3,21 @@ ## Core Java Collections Cookbooks and Examples ### Relevant Articles: -- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list) -- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) -- [Random List Element](http://www.baeldung.com/java-random-list-element) - [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections) -- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list) -- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list) -- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) - [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset) - [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection) - [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque) - [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset) - [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set) -- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) - [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size) -- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) - [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering) -- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list) -- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list) - [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset) - [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) - [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) -- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) - [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) -- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) -- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) -- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list) - [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe) -- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) - [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall) - [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance) - [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity) @@ -40,13 +25,8 @@ - [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections) - [Guide to EnumSet](https://www.baeldung.com/java-enumset) - [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements) -- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) -- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items) - [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections) - [Sorting in Java](http://www.baeldung.com/java-sorting) -- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist) -- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception) - [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split) -- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) -- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line) -- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist) +- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map) +- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) diff --git a/core-java/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java b/core-java-collections/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java similarity index 100% rename from core-java/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java rename to core-java-collections/src/main/java/com/baeldung/iteratorguide/IteratorGuide.java diff --git a/core-java-collections/src/test/java/com/baeldung/hashmapvshashtable/HashmapVsHashtableDifferenceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/hashmapvshashtable/HashmapVsHashtableDifferenceUnitTest.java new file mode 100644 index 0000000000..5218332d60 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/hashmapvshashtable/HashmapVsHashtableDifferenceUnitTest.java @@ -0,0 +1,98 @@ +package com.baeldung.hashmapvshashtable; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.junit.Test; + +import com.google.common.collect.Lists; + +public class HashmapVsHashtableDifferenceUnitTest { + + // null values + @Test(expected = NullPointerException.class) + public void givenHashtable_whenAddNullKey_thenNullPointerExceptionThrown() { + Hashtable table = new Hashtable(); + table.put(null, "value"); + } + + @Test(expected = NullPointerException.class) + public void givenHashtable_whenAddNullValue_thenNullPointerExceptionThrown() { + Hashtable table = new Hashtable(); + table.put("key", null); + } + + @Test + public void givenHashmap_whenAddNullKeyAndValue_thenObjectAdded() { + HashMap map = new HashMap(); + map.put(null, "value"); + map.put("key1", null); + map.put("key2", null); + + assertEquals(3, map.size()); + } + + // fail-fast iterator + @Test(expected = ConcurrentModificationException.class) + public void givenHashmap_whenModifyUnderlyingCollection_thenConcurrentModificationExceptionThrown() { + HashMap map = new HashMap(); + map.put("key1", "value1"); + map.put("key2", "value2"); + map.put("key3", "value3"); + + Iterator iterator = map.keySet().iterator(); + while(iterator.hasNext()){ + iterator.next(); + map.put("key4", "value4"); + } + } + + @Test + public void givenHashtable_whenModifyUnderlyingCollection_thenItHasNoEffectOnIteratedCollection() { + Hashtable table = new Hashtable(); + table.put("key1", "value1"); + table.put("key2", "value2"); + + List keysSelected = Lists.newArrayList(); + Enumeration keys = table.keys(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + keysSelected.add(key); + + if (key.equals("key1")) { + table.put("key3", "value3"); + } + } + + assertEquals(2, keysSelected.size()); + } + + // synchronized map + @Test + public void givenHashmap_thenCreateSynchronizedMap() { + HashMap map = new HashMap(); + map.put("key1", "value1"); + map.put("key2", "value2"); + map.put("key3", "value3"); + + Set> set = map.entrySet(); + synchronized (map) { + Iterator> it = set.iterator(); + while(it.hasNext()) { + Map.Entry elem = (Map.Entry)it.next(); + } + } + + Map syncMap = Collections.synchronizedMap(map); + } +} diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java deleted file mode 100644 index 09ecebe47b..0000000000 --- a/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.java.collections; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import org.junit.Assert; -import org.junit.Test; - -class CollectionsEmpty { - - @Test - public void givenArrayList_whenAddingElement_addsNewElement() { - ArrayList mutableList = new ArrayList<>(); - mutableList.add("test"); - - Assert.assertEquals(mutableList.size(), 1); - Assert.assertEquals(mutableList.get(0), "test"); - } - - @Test(expected = UnsupportedOperationException.class) - public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() { - List immutableList = Collections.emptyList(); - immutableList.add("test"); - } - -} diff --git a/core-java-collections/src/test/java/org/baeldung/java/lists/ListJUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/lists/ListJUnitTest.java deleted file mode 100644 index 7dddf6c2ce..0000000000 --- a/core-java-collections/src/test/java/org/baeldung/java/lists/ListJUnitTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.java.lists; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -public class ListJUnitTest { - - private final List list1 = Arrays.asList("1", "2", "3", "4"); - private final List list2 = Arrays.asList("1", "2", "3", "4"); - private final List list3 = Arrays.asList("1", "2", "4", "3"); - - @Test - public void whenTestingForEquality_ShouldBeEqual() throws Exception { - Assert.assertEquals(list1, list2); - Assert.assertNotSame(list1, list2); - Assert.assertNotEquals(list1, list3); - } -} diff --git a/core-java-concurrency/.gitignore b/core-java-concurrency-advanced/.gitignore similarity index 100% rename from core-java-concurrency/.gitignore rename to core-java-concurrency-advanced/.gitignore diff --git a/core-java-concurrency/README.md b/core-java-concurrency-advanced/README.md similarity index 52% rename from core-java-concurrency/README.md rename to core-java-concurrency-advanced/README.md index fbe50c2dfa..bcbec9d687 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency-advanced/README.md @@ -1,33 +1,24 @@ ========= -## Core Java Concurrency Examples +## Core Java Concurrency Advanced Examples ### Relevant Articles: -- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) -- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) - [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) -- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) - [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) - [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks) - [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal) -- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) - [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator) - [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers) - [Guide to the Java Phaser](http://www.baeldung.com/java-phaser) -- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized) - [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables) - [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier) - [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile) -- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) - [Semaphores in Java](http://www.baeldung.com/java-semaphore) - [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread) -- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread) -- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop) -- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads) -- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify) - [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule) -- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) -- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle) -- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) - [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield) - [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads) +- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch) +- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) +- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) +- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) \ No newline at end of file diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency-advanced/pom.xml similarity index 78% rename from core-java-concurrency/pom.xml rename to core-java-concurrency-advanced/pom.xml index bd22253c2c..1209cba619 100644 --- a/core-java-concurrency/pom.xml +++ b/core-java-concurrency-advanced/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - core-java-concurrency + core-java-concurrency-advanced 0.1.0-SNAPSHOT jar - core-java-concurrency + core-java-concurrency-advanced com.baeldung @@ -47,10 +47,20 @@ ${avaitility.version} test + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator-annprocess.version} + - core-java-concurrency + core-java-concurrency-advanced src/main/resources @@ -69,6 +79,8 @@ 3.6.1 1.7.0 + 1.19 + 1.19 diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java similarity index 94% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java index e3a1629ce1..ef6b7ee8c8 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java @@ -1,13 +1,13 @@ -package com.baeldung.concurrent.atomic; - -public class SafeCounterWithLock { - private volatile int counter; - - int getValue() { - return counter; - } - - synchronized void increment() { - counter++; - } -} +package com.baeldung.concurrent.atomic; + +public class SafeCounterWithLock { + private volatile int counter; + + int getValue() { + return counter; + } + + synchronized void increment() { + counter++; + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java similarity index 96% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java index 18ade35efb..8b2aebba7c 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java @@ -1,21 +1,21 @@ -package com.baeldung.concurrent.atomic; - -import java.util.concurrent.atomic.AtomicInteger; - -public class SafeCounterWithoutLock { - private final AtomicInteger counter = new AtomicInteger(0); - - int getValue() { - return counter.get(); - } - - void increment() { - while(true) { - int existingValue = getValue(); - int newValue = existingValue + 1; - if(counter.compareAndSet(existingValue, newValue)) { - return; - } - } - } -} +package com.baeldung.concurrent.atomic; + +import java.util.concurrent.atomic.AtomicInteger; + +public class SafeCounterWithoutLock { + private final AtomicInteger counter = new AtomicInteger(0); + + int getValue() { + return counter.get(); + } + + void increment() { + while(true) { + int existingValue = getValue(); + int newValue = existingValue + 1; + if(counter.compareAndSet(existingValue, newValue)) { + return; + } + } + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java similarity index 94% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java index 500ef5bd7e..290c26b73d 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java @@ -1,13 +1,13 @@ -package com.baeldung.concurrent.atomic; - -public class UnsafeCounter { - private int counter; - - int getValue() { - return counter; - } - - void increment() { - counter++; - } -} +package com.baeldung.concurrent.atomic; + +public class UnsafeCounter { + private int counter; + + int getValue() { + return counter; + } + + void increment() { + counter++; + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/BrokenWorker.java diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java new file mode 100644 index 0000000000..08c7eeec03 --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java @@ -0,0 +1,33 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.concurrent.CountDownLatch; + +public class CountdownLatchCountExample { + + private int count; + + public CountdownLatchCountExample(int count) { + this.count = count; + } + + public boolean callTwiceInSameThread() { + CountDownLatch countDownLatch = new CountDownLatch(count); + Thread t = new Thread(() -> { + countDownLatch.countDown(); + countDownLatch.countDown(); + }); + t.start(); + + try { + countDownLatch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return countDownLatch.getCount() == 0; + } + + public static void main(String[] args) { + CountdownLatchCountExample ex = new CountdownLatchCountExample(2); + System.out.println("Is CountDown Completed : " + ex.callTwiceInSameThread()); + } +} diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java new file mode 100644 index 0000000000..1828b7f91e --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java @@ -0,0 +1,41 @@ +package com.baeldung.concurrent.countdownlatch; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +public class CountdownLatchResetExample { + + private int count; + private int threadCount; + private final AtomicInteger updateCount; + + CountdownLatchResetExample(int count, int threadCount) { + updateCount = new AtomicInteger(0); + this.count = count; + this.threadCount = threadCount; + } + + public int countWaits() { + CountDownLatch countDownLatch = new CountDownLatch(count); + ExecutorService es = Executors.newFixedThreadPool(threadCount); + for (int i = 0; i < threadCount; i++) { + es.execute(() -> { + long prevValue = countDownLatch.getCount(); + countDownLatch.countDown(); + if (countDownLatch.getCount() != prevValue) { + updateCount.incrementAndGet(); + } + }); + } + + es.shutdown(); + return updateCount.get(); + } + + public static void main(String[] args) { + CountdownLatchResetExample ex = new CountdownLatchResetExample(5, 20); + System.out.println("Count : " + ex.countWaits()); + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/WaitingWorker.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java new file mode 100644 index 0000000000..7c1299da62 --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java @@ -0,0 +1,45 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +public class CyclicBarrierCompletionMethodExample { + + private int count; + private int threadCount; + private final AtomicInteger updateCount; + + CyclicBarrierCompletionMethodExample(int count, int threadCount) { + updateCount = new AtomicInteger(0); + this.count = count; + this.threadCount = threadCount; + } + + public int countTrips() { + + CyclicBarrier cyclicBarrier = new CyclicBarrier(count, () -> { + updateCount.incrementAndGet(); + }); + + ExecutorService es = Executors.newFixedThreadPool(threadCount); + for (int i = 0; i < threadCount; i++) { + es.execute(() -> { + try { + cyclicBarrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); + } + }); + } + es.shutdown(); + return updateCount.get(); + } + + public static void main(String[] args) { + CyclicBarrierCompletionMethodExample ex = new CyclicBarrierCompletionMethodExample(5, 20); + System.out.println("Count : " + ex.countTrips()); + } +} diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java new file mode 100644 index 0000000000..9d637b428b --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java @@ -0,0 +1,32 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +public class CyclicBarrierCountExample { + + private int count; + + public CyclicBarrierCountExample(int count) { + this.count = count; + } + + public boolean callTwiceInSameThread() { + CyclicBarrier cyclicBarrier = new CyclicBarrier(count); + Thread t = new Thread(() -> { + try { + cyclicBarrier.await(); + cyclicBarrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); + } + }); + t.start(); + return cyclicBarrier.isBroken(); + } + + public static void main(String[] args) { + CyclicBarrierCountExample ex = new CyclicBarrierCountExample(7); + System.out.println("Count : " + ex.callTwiceInSameThread()); + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java new file mode 100644 index 0000000000..76b6198bc4 --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java @@ -0,0 +1,46 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +public class CyclicBarrierResetExample { + + private int count; + private int threadCount; + private final AtomicInteger updateCount; + + CyclicBarrierResetExample(int count, int threadCount) { + updateCount = new AtomicInteger(0); + this.count = count; + this.threadCount = threadCount; + } + + public int countWaits() { + + CyclicBarrier cyclicBarrier = new CyclicBarrier(count); + + ExecutorService es = Executors.newFixedThreadPool(threadCount); + for (int i = 0; i < threadCount; i++) { + es.execute(() -> { + try { + if (cyclicBarrier.getNumberWaiting() > 0) { + updateCount.incrementAndGet(); + } + cyclicBarrier.await(); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); + } + }); + } + es.shutdown(); + return updateCount.get(); + } + + public static void main(String[] args) { + CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7, 20); + System.out.println("Count : " + ex.countWaits()); + } +} diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java new file mode 100644 index 0000000000..492466e0c3 --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java @@ -0,0 +1,12 @@ +package com.baeldung.concurrent.daemon; + +public class MultipleThreadsExample { + public static void main(String[] args) { + NewThread t1 = new NewThread(); + t1.setName("MyThread-1"); + NewThread t2 = new NewThread(); + t2.setName("MyThread-2"); + t1.start(); + t2.start(); + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/NewThread.java similarity index 60% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/NewThread.java index 4d87978070..370ce99c09 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/NewThread.java @@ -1,14 +1,18 @@ package com.baeldung.concurrent.daemon; public class NewThread extends Thread { - public void run() { long startTime = System.currentTimeMillis(); while (true) { for (int i = 0; i < 10; i++) { - System.out.println("New Thread is running..." + i); + System.out.println(this.getName() + ": New Thread is running..." + i); + try { + //Wait for one sec so it doesn't print too fast + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - // prevent the Thread to run forever. It will finish it's execution after 2 seconds if (System.currentTimeMillis() - startTime > 2000) { Thread.currentThread().interrupt(); diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java new file mode 100644 index 0000000000..16d8b2be1e --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java @@ -0,0 +1,8 @@ +package com.baeldung.concurrent.daemon; + +public class SingleThreadExample { + public static void main(String[] args) { + NewThread t = new NewThread(); + t.start(); + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/diningphilosophers/DiningPhilosophers.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddSemaphore.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddSemaphore.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddSemaphore.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddSemaphore.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddWaitNotify.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddWaitNotify.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddWaitNotify.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/evenandodd/PrintEvenOddWaitNotify.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/ReentrantLockWithCondition.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/SharedObjectWithLock.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/StampedLockDemo.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLock.java diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/parameter/AverageCalculator.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/parameter/AverageCalculator.java new file mode 100644 index 0000000000..a548b5d4a7 --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/parameter/AverageCalculator.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.parameter; + +import java.util.concurrent.Callable; +import java.util.stream.IntStream; + +public class AverageCalculator implements Callable { + + int[] numbers; + + public AverageCalculator(int... parameter) { + this.numbers = parameter == null ? new int[0] : parameter; + } + + @Override + public Double call() throws Exception { + return IntStream.of(this.numbers) + .average() + .orElse(0d); + } +} diff --git a/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/parameter/ParameterizedThreadExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/parameter/ParameterizedThreadExample.java new file mode 100644 index 0000000000..73c61f3fb1 --- /dev/null +++ b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/parameter/ParameterizedThreadExample.java @@ -0,0 +1,32 @@ +package com.baeldung.concurrent.parameter; + +import java.util.concurrent.Callable; +import java.util.stream.IntStream; + +public class ParameterizedThreadExample { + + public static void parameterisedThreadAnonymousClass() { + final String parameter = "123"; + Thread parameterizedThread = new Thread(new Runnable() { + + @Override + public void run() { + System.out.println(Thread.currentThread() + .getName() + " : " + parameter); + } + }); + + parameterizedThread.start(); + } + + public static Callable sumCalculator(int... numbers) { + return () -> numbers != null ? IntStream.of(numbers) + .sum() : 0; + } + + public static Callable averageCalculator(int... numbers) { + return () -> numbers != null ? IntStream.of(numbers) + .average() + .orElse(0d) : 0d; + } +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/prioritytaskexecution/Job.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/prioritytaskexecution/JobPriority.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/prioritytaskexecution/JobPriority.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/prioritytaskexecution/JobPriority.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/prioritytaskexecution/JobPriority.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobScheduler.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobScheduler.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobScheduler.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobScheduler.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/semaphores/CounterUsingMutex.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/semaphores/DelayQueueUsingTimedSemaphore.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/semaphores/LoginQueueUsingSemaphore.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/yield/ThreadYield.java diff --git a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java similarity index 100% rename from core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java diff --git a/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java similarity index 100% rename from core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java diff --git a/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java similarity index 100% rename from core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/Context.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/Context.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/UserRepository.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocal/UserRepository.java diff --git a/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java similarity index 100% rename from core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarkRunner.java diff --git a/core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java similarity index 100% rename from core-java/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadlocalrandom/ThreadLocalRandomBenchMarker.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadpool/CountingTask.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadpool/CountingTask.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/threadpool/TreeNode.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/threadpool/TreeNode.java diff --git a/core-java-concurrency/src/main/java/log4j.properties b/core-java-concurrency-advanced/src/main/java/log4j.properties similarity index 100% rename from core-java-concurrency/src/main/java/log4j.properties rename to core-java-concurrency-advanced/src/main/java/log4j.properties diff --git a/core-java-concurrency/src/main/resources/logback.xml b/core-java-concurrency-advanced/src/main/resources/logback.xml similarity index 100% rename from core-java-concurrency/src/main/resources/logback.xml rename to core-java-concurrency-advanced/src/main/resources/logback.xml diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/adder/LongAdderUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java similarity index 97% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java index 4eead471f8..c3c44b40cf 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java @@ -1,38 +1,38 @@ -package com.baeldung.concurrent.atomic; - -import static org.junit.Assert.assertEquals; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.stream.IntStream; - -import org.junit.Test; - -public class ThreadSafeCounterIntegrationTest { - - @Test - public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - SafeCounterWithLock safeCounter = new SafeCounterWithLock(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(safeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, safeCounter.getValue()); - } - - @Test - public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(safeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, safeCounter.getValue()); - } - -} +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +public class ThreadSafeCounterIntegrationTest { + + @Test + public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithLock safeCounter = new SafeCounterWithLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + + @Test + public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java similarity index 97% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java index cc7cc18bb5..bf451e58de 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java @@ -1,33 +1,33 @@ -package com.baeldung.concurrent.atomic; - -import static org.junit.Assert.assertEquals; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.stream.IntStream; - -import org.junit.Test; - -/** - * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling - * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will - * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads - * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this - * test from build by adding this in manual test - */ -public class ThreadUnsafeCounterManualTest { - - @Test - public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { - ExecutorService service = Executors.newFixedThreadPool(3); - UnsafeCounter unsafeCounter = new UnsafeCounter(); - - IntStream.range(0, 1000) - .forEach(count -> service.submit(unsafeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); - - assertEquals(1000, unsafeCounter.getValue()); - } - -} +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +/** + * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling + * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will + * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads + * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this + * test from build by adding this in manual test + */ +public class ThreadUnsafeCounterManualTest { + + @Test + public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + UnsafeCounter unsafeCounter = new UnsafeCounter(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(unsafeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, unsafeCounter.getValue()); + } + +} diff --git a/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java new file mode 100644 index 0000000000..835efa53f2 --- /dev/null +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.concurrent.countdownlatch; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class CountdownLatchCountExampleUnitTest { + + @Test + public void whenCountDownLatch_completed() { + CountdownLatchCountExample ex = new CountdownLatchCountExample(2); + boolean isCompleted = ex.callTwiceInSameThread(); + assertTrue(isCompleted); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java diff --git a/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java new file mode 100644 index 0000000000..d2d43f6312 --- /dev/null +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.concurrent.countdownlatch; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class CountdownLatchResetExampleUnitTest { + + @Test + public void whenCountDownLatch_noReset() { + CountdownLatchResetExample ex = new CountdownLatchResetExample(7,20); + int lineCount = ex.countWaits(); + assertTrue(lineCount <= 7); + } +} diff --git a/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java new file mode 100644 index 0000000000..310063c86c --- /dev/null +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CyclicBarrierCompletionMethodExampleUnitTest { + + @Test + public void whenCyclicBarrier_countTrips() { + CyclicBarrierCompletionMethodExample ex = new CyclicBarrierCompletionMethodExample(7,20); + int lineCount = ex.countTrips(); + assertEquals(2, lineCount); + } +} diff --git a/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java new file mode 100644 index 0000000000..9b7f3d9945 --- /dev/null +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +public class CyclicBarrierCountExampleUnitTest { + + @Test + public void whenCyclicBarrier_notCompleted() { + CyclicBarrierCountExample ex = new CyclicBarrierCountExample(2); + boolean isCompleted = ex.callTwiceInSameThread(); + assertFalse(isCompleted); + } +} diff --git a/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java new file mode 100644 index 0000000000..8d2b148f06 --- /dev/null +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class CyclicBarrierResetExampleUnitTest { + + @Test + public void whenCyclicBarrier_reset() { + CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7,20); + int lineCount = ex.countWaits(); + assertTrue(lineCount > 7); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/locks/SharedObjectWithLockManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java diff --git a/core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java diff --git a/core-java-concurrency-advanced/src/test/java/com/baeldung/parameters/ParameterizedThreadUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/parameters/ParameterizedThreadUnitTest.java new file mode 100644 index 0000000000..21b374e609 --- /dev/null +++ b/core-java-concurrency-advanced/src/test/java/com/baeldung/parameters/ParameterizedThreadUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.parameters; + +import com.baeldung.concurrent.parameter.AverageCalculator; +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class ParameterizedThreadUnitTest { + + @Test + public void whenSendingParameterToCallable_thenSuccessful() throws Exception { + ExecutorService executorService = Executors.newSingleThreadExecutor(); + Future result = executorService.submit(new AverageCalculator(1, 2, 3)); + try { + assertEquals(Double.valueOf(2.0), result.get()); + } finally { + executorService.shutdown(); + } + } + + @Test + public void whenParametersToThreadWithLamda_thenParametersPassedCorrectly() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + int[] numbers = new int[] { 4, 5, 6 }; + try { + Future sumResult = executorService.submit(() -> IntStream.of(numbers) + .sum()); + Future averageResult = executorService.submit(() -> IntStream.of(numbers) + .average() + .orElse(0d)); + assertEquals(Integer.valueOf(15), sumResult.get()); + assertEquals(Double.valueOf(5.0), averageResult.get()); + } finally { + executorService.shutdown(); + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/thread/join/ThreadJoinUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/threadlocal/ThreadLocalIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java diff --git a/core-java-concurrency/src/test/resources/.gitignore b/core-java-concurrency-advanced/src/test/resources/.gitignore similarity index 100% rename from core-java-concurrency/src/test/resources/.gitignore rename to core-java-concurrency-advanced/src/test/resources/.gitignore diff --git a/core-java-concurrency-basic/.gitignore b/core-java-concurrency-basic/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-concurrency-basic/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-concurrency-basic/README.md b/core-java-concurrency-basic/README.md new file mode 100644 index 0000000000..1c43149d03 --- /dev/null +++ b/core-java-concurrency-basic/README.md @@ -0,0 +1,17 @@ +========= + +## Core Java Concurrency Basic Examples + +### Relevant Articles: +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial) +- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future) +- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep) +- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized) +- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) +- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread) +- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop) +- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads) +- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify) +- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle) +- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) \ No newline at end of file diff --git a/core-java-concurrency-basic/pom.xml b/core-java-concurrency-basic/pom.xml new file mode 100644 index 0000000000..3544403aca --- /dev/null +++ b/core-java-concurrency-basic/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.baeldung + core-java-concurrency-basic + 0.1.0-SNAPSHOT + jar + core-java-concurrency-basic + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + + + core-java-concurrency-basic + + + src/main/resources + true + + + + + + + 3.5 + + 3.6.1 + 1.7.0 + + + diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java new file mode 100644 index 0000000000..0989195ba7 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java @@ -0,0 +1,52 @@ +package com.baeldung.concurrent.Scheduledexecutorservice; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +public class ScheduledExecutorServiceDemo { + + private void execute() { + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + getTasksToRun().apply(executorService); + executorService.shutdown(); + } + + private void executeWithMultiThread() { + ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); + getTasksToRun().apply(executorService); + executorService.shutdown(); + } + + private Function getTasksToRun() { + return (executorService -> { + ScheduledFuture scheduledFuture1 = executorService.schedule(() -> { + // Task + }, 1, TimeUnit.SECONDS); + + ScheduledFuture scheduledFuture2 = executorService.scheduleAtFixedRate(() -> { + // Task + }, 1, 10, TimeUnit.SECONDS); + + ScheduledFuture scheduledFuture3 = executorService.scheduleWithFixedDelay(() -> { + // Task + }, 1, 10, TimeUnit.SECONDS); + + ScheduledFuture scheduledFuture4 = executorService.schedule(() -> { + // Task + return "Hellow world"; + }, 1, TimeUnit.SECONDS); + return null; + }); + } + + public static void main(String... args) { + ScheduledExecutorServiceDemo demo = new ScheduledExecutorServiceDemo(); + demo.execute(); + demo.executeWithMultiThread(); + } + + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/Invoker.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executor/Invoker.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/executor/Invoker.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executor/Invoker.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/Task.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executorservice/Task.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/Task.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/executorservice/Task.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/future/FactorialSquareCalculator.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/future/FutureDemo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/future/FutureDemo.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/future/FutureDemo.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/EventLoggingTask.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/runnable/EventLoggingTask.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/EventLoggingTask.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/runnable/EventLoggingTask.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/TaskRunner.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/runnable/TaskRunner.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/runnable/TaskRunner.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/runnable/TaskRunner.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/sleepwait/ThreadA.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/sleepwait/ThreadB.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/sleepwait/WaitSleepExample.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedBlocks.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizedMethods.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Task.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadfactory/Task.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadfactory/Task.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadfactory/Task.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/BlockedState.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/BlockedState.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/BlockedState.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/BlockedState.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/NewState.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/NewState.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/NewState.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/NewState.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/RunnableState.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/RunnableState.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/RunnableState.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/RunnableState.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/TerminatedState.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/TerminatedState.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/TerminatedState.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/TerminatedState.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/TimedWaitingState.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/TimedWaitingState.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/TimedWaitingState.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/TimedWaitingState.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/WaitingState.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/WaitingState.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/threadlifecycle/WaitingState.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadlifecycle/WaitingState.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Data.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/Data.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Data.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/Data.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/NetworkDriver.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/NetworkDriver.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/NetworkDriver.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/NetworkDriver.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Receiver.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/Receiver.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Receiver.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/Receiver.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Sender.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/Sender.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Sender.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/waitandnotify/Sender.java diff --git a/spring-mybatis/src/main/resources/logback.xml b/core-java-concurrency-basic/src/main/resources/logback.xml similarity index 57% rename from spring-mybatis/src/main/resources/logback.xml rename to core-java-concurrency-basic/src/main/resources/logback.xml index 7d900d8ea8..56af2d397e 100644 --- a/spring-mybatis/src/main/resources/logback.xml +++ b/core-java-concurrency-basic/src/main/resources/logback.xml @@ -7,6 +7,12 @@ + + + + + + diff --git a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishManualTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishManualTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/future/FactorialSquareCalculatorUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadManualTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/stopping/StopThreadManualTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadManualTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/stopping/StopThreadManualTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/waitandnotify/NetworkIntegrationTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/waitandnotify/NetworkIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/waitandnotify/NetworkIntegrationTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/waitandnotify/NetworkIntegrationTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java b/core-java-concurrency-basic/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java rename to core-java-concurrency-basic/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java diff --git a/spring-rest-template/.gitignore b/core-java-concurrency-basic/src/test/resources/.gitignore similarity index 92% rename from spring-rest-template/.gitignore rename to core-java-concurrency-basic/src/test/resources/.gitignore index afdfaa6ded..83c05e60c8 100644 --- a/spring-rest-template/.gitignore +++ b/core-java-concurrency-basic/src/test/resources/.gitignore @@ -6,7 +6,6 @@ /data /src/main/webapp/WEB-INF/classes */META-INF/* -*/.idea/* # Packaged files # *.jar diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java deleted file mode 100644 index b77019eea5..0000000000 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.concurrent.Scheduledexecutorservice; - -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -public class ScheduledExecutorServiceDemo { - - public void execute() { - ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - - ScheduledFuture scheduledFuture = executorService.schedule(() -> { - // Task - }, 1, TimeUnit.SECONDS); - - executorService.scheduleAtFixedRate(() -> { - // Task - }, 1, 10, TimeUnit.SECONDS); - - executorService.scheduleWithFixedDelay(() -> { - // Task - }, 1, 10, TimeUnit.SECONDS); - - Future future = executorService.schedule(() -> { - // Task - return "Hellow world"; - }, 1, TimeUnit.SECONDS); - - executorService.shutdown(); - } - -} diff --git a/core-java-io/README.md b/core-java-io/README.md index c81e466b57..2ad980ca6a 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -34,3 +34,6 @@ - [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist) - [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream) - [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array) +- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader) +- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) +- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) \ No newline at end of file diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml index efa32b8e3e..1f2d52de81 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -160,6 +160,17 @@ ${opencsv.version} test + + + org.apache.tika + tika-core + ${tika.version} + + + net.sf.jmimemagic + jmimemagic + ${jmime-magic.version} + @@ -236,7 +247,7 @@ - 2.8.5 + 2.9.7 3.5 @@ -264,6 +275,9 @@ 2.1.0.1 1.19 2.4.5 + + 1.18 + 0.1.5 \ No newline at end of file diff --git a/core-java-io/src/main/java/com/baeldung/download/FileDownload.java b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java index c7dd154023..a099406d4c 100644 --- a/core-java-io/src/main/java/com/baeldung/download/FileDownload.java +++ b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java @@ -45,6 +45,7 @@ public class FileDownload { FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) { fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE); + fileOutputStream.close(); } } diff --git a/core-java/src/main/java/com/baeldung/extension/Extension.java b/core-java-io/src/main/java/com/baeldung/extension/Extension.java similarity index 100% rename from core-java/src/main/java/com/baeldung/extension/Extension.java rename to core-java-io/src/main/java/com/baeldung/extension/Extension.java diff --git a/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java b/core-java-io/src/test/java/com/baeldung/extension/ExtensionUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java rename to core-java-io/src/test/java/com/baeldung/extension/ExtensionUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeUnitTest.java b/core-java-io/src/test/java/com/baeldung/java/mimetype/MimeTypeUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/java/mimetype/MimeTypeUnitTest.java rename to core-java-io/src/test/java/com/baeldung/java/mimetype/MimeTypeUnitTest.java diff --git a/core-java/src/test/resources/META-INF/mime.types b/core-java-io/src/test/resources/META-INF/mime.types similarity index 100% rename from core-java/src/test/resources/META-INF/mime.types rename to core-java-io/src/test/resources/META-INF/mime.types diff --git a/core-java/src/test/resources/product.png b/core-java-io/src/test/resources/product.png similarity index 100% rename from core-java/src/test/resources/product.png rename to core-java-io/src/test/resources/product.png diff --git a/core-java-lang-oop/.gitignore b/core-java-lang-oop/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-lang-oop/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-lang-oop/README.md b/core-java-lang-oop/README.md new file mode 100644 index 0000000000..bbc3d26c99 --- /dev/null +++ b/core-java-lang-oop/README.md @@ -0,0 +1,24 @@ +========= + +## Core Java Lang OOP Cookbooks and Examples + +### Relevant Articles: +- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode) +- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) +- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) +- [Polymorphism in Java](http://www.baeldung.com/java-polymorphism) +- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override) +- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy) +- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance) +- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting) +- [The "final" Keyword in Java](http://www.baeldung.com/java-final) +- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure) +- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) +- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding) +- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers) +- [Guide to the super Java Keyword](http://www.baeldung.com/java-super) +- [Guide to the this Java Keyword](http://www.baeldung.com/java-this) +- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object) +- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) +- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) +- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts) diff --git a/core-java-lang-oop/pom.xml b/core-java-lang-oop/pom.xml new file mode 100644 index 0000000000..262408c024 --- /dev/null +++ b/core-java-lang-oop/pom.xml @@ -0,0 +1,91 @@ + + 4.0.0 + com.baeldung + core-java-lang-oop + 0.1.0-SNAPSHOT + jar + core-java-lang-oop + + + 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} + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + nl.jqno.equalsverifier + equalsverifier + ${equalsverifier.version} + test + + + + + core-java-lang-oop + + + src/main/resources + true + + + + + + + + 2.8.5 + 2.8.2 + + + 3.5 + 1.16.12 + + 3.10.0 + 3.0.3 + + + diff --git a/core-java-lang/src/main/java/com/baeldung/accessmodifiers/Public.java b/core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/Public.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/accessmodifiers/Public.java rename to core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/Public.java diff --git a/core-java-lang/src/main/java/com/baeldung/accessmodifiers/SubClass.java b/core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/SubClass.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/accessmodifiers/SubClass.java rename to core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/SubClass.java diff --git a/core-java-lang/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java b/core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java rename to core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java diff --git a/core-java-lang/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java b/core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java rename to core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java diff --git a/core-java-lang/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java b/core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java rename to core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java diff --git a/core-java-lang/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java b/core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java rename to core-java-lang-oop/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java diff --git a/core-java-lang/src/main/java/com/baeldung/casting/Animal.java b/core-java-lang-oop/src/main/java/com/baeldung/casting/Animal.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/casting/Animal.java rename to core-java-lang-oop/src/main/java/com/baeldung/casting/Animal.java diff --git a/core-java-lang/src/main/java/com/baeldung/casting/AnimalFeeder.java b/core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeeder.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/casting/AnimalFeeder.java rename to core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeeder.java diff --git a/core-java-lang/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java b/core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java rename to core-java-lang-oop/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java diff --git a/core-java-lang/src/main/java/com/baeldung/casting/Cat.java b/core-java-lang-oop/src/main/java/com/baeldung/casting/Cat.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/casting/Cat.java rename to core-java-lang-oop/src/main/java/com/baeldung/casting/Cat.java diff --git a/core-java-lang/src/main/java/com/baeldung/casting/Dog.java b/core-java-lang-oop/src/main/java/com/baeldung/casting/Dog.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/casting/Dog.java rename to core-java-lang-oop/src/main/java/com/baeldung/casting/Dog.java diff --git a/core-java-lang/src/main/java/com/baeldung/casting/Mew.java b/core-java-lang-oop/src/main/java/com/baeldung/casting/Mew.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/casting/Mew.java rename to core-java-lang-oop/src/main/java/com/baeldung/casting/Mew.java diff --git a/core-java/src/main/java/com/baeldung/constructors/BankAccount.java b/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java similarity index 100% rename from core-java/src/main/java/com/baeldung/constructors/BankAccount.java rename to core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java diff --git a/core-java/src/main/java/com/baeldung/constructors/Transaction.java b/core-java-lang-oop/src/main/java/com/baeldung/constructors/Transaction.java similarity index 100% rename from core-java/src/main/java/com/baeldung/constructors/Transaction.java rename to core-java-lang-oop/src/main/java/com/baeldung/constructors/Transaction.java diff --git a/core-java-lang/src/main/java/com/baeldung/deepcopy/Address.java b/core-java-lang-oop/src/main/java/com/baeldung/deepcopy/Address.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/deepcopy/Address.java rename to core-java-lang-oop/src/main/java/com/baeldung/deepcopy/Address.java diff --git a/core-java-lang/src/main/java/com/baeldung/deepcopy/User.java b/core-java-lang-oop/src/main/java/com/baeldung/deepcopy/User.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/deepcopy/User.java rename to core-java-lang-oop/src/main/java/com/baeldung/deepcopy/User.java diff --git a/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Money.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Money.java new file mode 100644 index 0000000000..60c043545d --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Money.java @@ -0,0 +1,36 @@ +package com.baeldung.equalshashcode; + +class Money { + + int amount; + String currencyCode; + + Money(int amount, String currencyCode) { + this.amount = amount; + this.currencyCode = currencyCode; + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Money)) + return false; + Money other = (Money)o; + boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null) + || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode)); + return this.amount == other.amount + && currencyCodeEquals; + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + amount; + if (currencyCode != null) { + result = 31 * result + currencyCode.hashCode(); + } + return result; + } + +} diff --git a/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Team.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Team.java new file mode 100644 index 0000000000..c2dee1de6b --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Team.java @@ -0,0 +1,39 @@ +package com.baeldung.equalshashcode; + +class Team { + + final String city; + final String department; + + Team(String city, String department) { + this.city = city; + this.department = department; + } + + @Override + public final boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Team)) + return false; + Team otherTeam = (Team)o; + boolean cityEquals = (this.city == null && otherTeam.city == null) + || this.city != null && this.city.equals(otherTeam.city); + boolean departmentEquals = (this.department == null && otherTeam.department == null) + || this.department != null && this.department.equals(otherTeam.department); + return cityEquals && departmentEquals; + } + + @Override + public final int hashCode() { + int result = 17; + if (city != null) { + result = 31 * result + city.hashCode(); + } + if (department != null) { + result = 31 * result + department.hashCode(); + } + return result; + } + +} diff --git a/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Voucher.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Voucher.java new file mode 100644 index 0000000000..19f46e0358 --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Voucher.java @@ -0,0 +1,38 @@ +package com.baeldung.equalshashcode; + +class Voucher { + + private Money value; + private String store; + + Voucher(int amount, String currencyCode, String store) { + this.value = new Money(amount, currencyCode); + this.store = store; + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Voucher)) + return false; + Voucher other = (Voucher)o; + boolean valueEquals = (this.value == null && other.value == null) + || (this.value != null && this.value.equals(other.value)); + boolean storeEquals = (this.store == null && other.store == null) + || (this.store != null && this.store.equals(other.store)); + return valueEquals && storeEquals; + } + + @Override + public int hashCode() { + int result = 17; + if (this.value != null) { + result = 31 * result + value.hashCode(); + } + if (this.store != null) { + result = 31 * result + store.hashCode(); + } + return result; + } +} \ No newline at end of file diff --git a/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongTeam.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongTeam.java new file mode 100644 index 0000000000..c4477aa790 --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongTeam.java @@ -0,0 +1,30 @@ +package com.baeldung.equalshashcode; + +/* (non-Javadoc) +* This class overrides equals, but it doesn't override hashCode. +* +* To see which problems this leads to: +* TeamUnitTest.givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue +*/ +class WrongTeam { + + String city; + String department; + + WrongTeam(String city, String department) { + this.city = city; + this.department = department; + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof WrongTeam)) + return false; + WrongTeam otherTeam = (WrongTeam)o; + return this.city == otherTeam.city + && this.department == otherTeam.department; + } + +} diff --git a/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java new file mode 100644 index 0000000000..97935bf8de --- /dev/null +++ b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java @@ -0,0 +1,47 @@ +package com.baeldung.equalshashcode; + +/* (non-Javadoc) +* This class extends the Money class that has overridden the equals method and once again overrides the equals method. +* +* To see which problems this leads to: +* MoneyUnitTest.givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric +*/ +class WrongVoucher extends Money { + + private String store; + + WrongVoucher(int amount, String currencyCode, String store) { + super(amount, currencyCode); + + this.store = store; + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof WrongVoucher)) + return false; + WrongVoucher other = (WrongVoucher)o; + boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null) + || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode)); + boolean storeEquals = (this.store == null && other.store == null) + || (this.store != null && this.store.equals(other.store)); + return this.amount == other.amount + && currencyCodeEquals + && storeEquals; + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + amount; + if (this.currencyCode != null) { + result = 31 * result + currencyCode.hashCode(); + } + if (this.store != null) { + result = 31 * result + store.hashCode(); + } + return result; + } +} \ No newline at end of file diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Shape.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/Shape.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Shape.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/Shape.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Square.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/Square.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/entities/Square.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/entities/Square.java diff --git a/core-java-lang/src/main/java/com/baeldung/finalkeyword/BlackCat.java b/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackCat.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/finalkeyword/BlackCat.java rename to core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackCat.java diff --git a/core-java-lang/src/main/java/com/baeldung/finalkeyword/BlackDog.java b/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackDog.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/finalkeyword/BlackDog.java rename to core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/BlackDog.java diff --git a/core-java-lang/src/main/java/com/baeldung/finalkeyword/Cat.java b/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Cat.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/finalkeyword/Cat.java rename to core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Cat.java diff --git a/core-java-lang/src/main/java/com/baeldung/finalkeyword/Dog.java b/core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Dog.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/finalkeyword/Dog.java rename to core-java-lang-oop/src/main/java/com/baeldung/finalkeyword/Dog.java diff --git a/core-java-lang/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java-lang-oop/src/main/java/com/baeldung/hashcode/entities/User.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/hashcode/entities/User.java rename to core-java-lang-oop/src/main/java/com/baeldung/hashcode/entities/User.java diff --git a/core-java-lang/src/main/java/com/baeldung/immutableobjects/Currency.java b/core-java-lang-oop/src/main/java/com/baeldung/immutableobjects/Currency.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/immutableobjects/Currency.java rename to core-java-lang-oop/src/main/java/com/baeldung/immutableobjects/Currency.java diff --git a/core-java-lang/src/main/java/com/baeldung/immutableobjects/Money.java b/core-java-lang-oop/src/main/java/com/baeldung/immutableobjects/Money.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/immutableobjects/Money.java rename to core-java-lang-oop/src/main/java/com/baeldung/immutableobjects/Money.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/ArmoredCar.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/ArmoredCar.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/ArmoredCar.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/ArmoredCar.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/BMW.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/BMW.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/BMW.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/BMW.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/Car.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Car.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/Car.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/Car.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/Employee.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Employee.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/Employee.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/Employee.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/Floatable.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Floatable.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/Floatable.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/Floatable.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/Flyable.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/Flyable.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/Flyable.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/Flyable.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/SpaceCar.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceCar.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/SpaceCar.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceCar.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritance/SpaceTraveller.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceTraveller.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritance/SpaceTraveller.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritance/SpaceTraveller.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/application/Application.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/application/Application.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/application/Application.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/application/Application.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Actress.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Computer.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Memory.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Person.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Person.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Person.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Person.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Processor.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/SoundCard.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/StandardMemory.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/StandardProcessor.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/StandardSoundCard.java diff --git a/core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java b/core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java rename to core-java-lang-oop/src/main/java/com/baeldung/inheritancecomposition/model/Waitress.java diff --git a/core-java-lang/src/main/java/com/baeldung/initializationguide/User.java b/core-java-lang-oop/src/main/java/com/baeldung/initializationguide/User.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/initializationguide/User.java rename to core-java-lang-oop/src/main/java/com/baeldung/initializationguide/User.java diff --git a/core-java-lang/src/main/java/com/baeldung/keyword/KeywordDemo.java b/core-java-lang-oop/src/main/java/com/baeldung/keyword/KeywordDemo.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/keyword/KeywordDemo.java rename to core-java-lang-oop/src/main/java/com/baeldung/keyword/KeywordDemo.java diff --git a/core-java-lang/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java b/core-java-lang-oop/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java rename to core-java-lang-oop/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java diff --git a/core-java-lang/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java b/core-java-lang-oop/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java rename to core-java-lang-oop/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java diff --git a/core-java-lang/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java b/core-java-lang-oop/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java rename to core-java-lang-oop/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java diff --git a/core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java b/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java rename to core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/application/Application.java diff --git a/core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java b/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java rename to core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Car.java diff --git a/core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java b/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java rename to core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/model/Vehicle.java diff --git a/core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java b/core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java rename to core-java-lang-oop/src/main/java/com/baeldung/methodoverloadingoverriding/util/Multiplier.java diff --git a/core-java-lang/src/main/java/com/baeldung/polymorphism/FileManager.java b/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/FileManager.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/polymorphism/FileManager.java rename to core-java-lang-oop/src/main/java/com/baeldung/polymorphism/FileManager.java diff --git a/core-java-lang/src/main/java/com/baeldung/polymorphism/GenericFile.java b/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/GenericFile.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/polymorphism/GenericFile.java rename to core-java-lang-oop/src/main/java/com/baeldung/polymorphism/GenericFile.java diff --git a/core-java-lang/src/main/java/com/baeldung/polymorphism/ImageFile.java b/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/ImageFile.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/polymorphism/ImageFile.java rename to core-java-lang-oop/src/main/java/com/baeldung/polymorphism/ImageFile.java diff --git a/core-java-lang/src/main/java/com/baeldung/polymorphism/TextFile.java b/core-java-lang-oop/src/main/java/com/baeldung/polymorphism/TextFile.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/polymorphism/TextFile.java rename to core-java-lang-oop/src/main/java/com/baeldung/polymorphism/TextFile.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/method/BaseMethodClass.java b/core-java-lang-oop/src/main/java/com/baeldung/scope/method/BaseMethodClass.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/scope/method/BaseMethodClass.java rename to core-java-lang-oop/src/main/java/com/baeldung/scope/method/BaseMethodClass.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/method/ChildMethodClass.java b/core-java-lang-oop/src/main/java/com/baeldung/scope/method/ChildMethodClass.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/scope/method/ChildMethodClass.java rename to core-java-lang-oop/src/main/java/com/baeldung/scope/method/ChildMethodClass.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java b/core-java-lang-oop/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java rename to core-java-lang-oop/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/variable/ChildVariable.java b/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ChildVariable.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/scope/variable/ChildVariable.java rename to core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ChildVariable.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/variable/HideVariable.java b/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/HideVariable.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/scope/variable/HideVariable.java rename to core-java-lang-oop/src/main/java/com/baeldung/scope/variable/HideVariable.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/variable/ParentVariable.java b/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ParentVariable.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/scope/variable/ParentVariable.java rename to core-java-lang-oop/src/main/java/com/baeldung/scope/variable/ParentVariable.java diff --git a/core-java-lang/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java b/core-java-lang-oop/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java rename to core-java-lang-oop/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java diff --git a/core-java-lang/src/main/java/com/baeldung/staticdemo/Car.java b/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Car.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/staticdemo/Car.java rename to core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Car.java diff --git a/core-java-lang/src/main/java/com/baeldung/staticdemo/Singleton.java b/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Singleton.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/staticdemo/Singleton.java rename to core-java-lang-oop/src/main/java/com/baeldung/staticdemo/Singleton.java diff --git a/core-java-lang/src/main/java/com/baeldung/staticdemo/StaticBlock.java b/core-java-lang-oop/src/main/java/com/baeldung/staticdemo/StaticBlock.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/staticdemo/StaticBlock.java rename to core-java-lang-oop/src/main/java/com/baeldung/staticdemo/StaticBlock.java diff --git a/core-java-lang/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java b/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java rename to core-java-lang-oop/src/main/java/com/baeldung/typeerasure/ArrayContentPrintUtil.java diff --git a/core-java-lang/src/main/java/com/baeldung/typeerasure/BoundStack.java b/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/BoundStack.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/typeerasure/BoundStack.java rename to core-java-lang-oop/src/main/java/com/baeldung/typeerasure/BoundStack.java diff --git a/core-java-lang/src/main/java/com/baeldung/typeerasure/IntegerStack.java b/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/IntegerStack.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/typeerasure/IntegerStack.java rename to core-java-lang-oop/src/main/java/com/baeldung/typeerasure/IntegerStack.java diff --git a/core-java-lang/src/main/java/com/baeldung/typeerasure/Stack.java b/core-java-lang-oop/src/main/java/com/baeldung/typeerasure/Stack.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/typeerasure/Stack.java rename to core-java-lang-oop/src/main/java/com/baeldung/typeerasure/Stack.java diff --git a/spring-rest-template/src/main/resources/logback.xml b/core-java-lang-oop/src/main/resources/logback.xml similarity index 57% rename from spring-rest-template/src/main/resources/logback.xml rename to core-java-lang-oop/src/main/resources/logback.xml index 7d900d8ea8..56af2d397e 100644 --- a/spring-rest-template/src/main/resources/logback.xml +++ b/core-java-lang-oop/src/main/resources/logback.xml @@ -7,6 +7,12 @@ + + + + + + diff --git a/core-java-lang/src/test/java/com/baeldung/casting/CastingUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/casting/CastingUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/casting/CastingUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/casting/CastingUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/deepcopy/DeepCopyUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/deepcopy/ShallowCopyUnitTest.java diff --git a/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java new file mode 100644 index 0000000000..60584fdb53 --- /dev/null +++ b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.equalshashcode; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +public class MoneyUnitTest { + + @Test + public void givenMoneyInstancesWithSameAmountAndCurrency_whenEquals_thenReturnsTrue() { + Money income = new Money(55, "USD"); + Money expenses = new Money(55, "USD"); + + assertTrue(income.equals(expenses)); + } + + @Test + public void givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() { + Money cash = new Money(42, "USD"); + WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon"); + + assertFalse(voucher.equals(cash)); + assertTrue(cash.equals(voucher)); + } + +} diff --git a/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java new file mode 100644 index 0000000000..a2de408796 --- /dev/null +++ b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.equalshashcode; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import nl.jqno.equalsverifier.EqualsVerifier; + +public class TeamUnitTest { + + @Test + public void givenMapKeyWithHashCode_whenSearched_thenReturnsCorrectValue() { + Map leaders = new HashMap<>(); + leaders.put(new Team("New York", "development"), "Anne"); + leaders.put(new Team("Boston", "development"), "Brian"); + leaders.put(new Team("Boston", "marketing"), "Charlie"); + + Team myTeam = new Team("New York", "development"); + String myTeamleader = leaders.get(myTeam); + + assertEquals("Anne", myTeamleader); + } + + @Test + public void givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue() { + Map leaders = new HashMap<>(); + leaders.put(new WrongTeam("New York", "development"), "Anne"); + leaders.put(new WrongTeam("Boston", "development"), "Brian"); + leaders.put(new WrongTeam("Boston", "marketing"), "Charlie"); + + WrongTeam myTeam = new WrongTeam("New York", "development"); + String myTeamleader = leaders.get(myTeam); + + assertFalse("Anne".equals(myTeamleader)); + } + + @Test + public void equalsContract() { + EqualsVerifier.forClass(Team.class).verify(); + } + +} diff --git a/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/entities/ComplexClassUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/entities/SquareClassUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/finalkeyword/FinalUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/inheritance/AppUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/inheritance/AppUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/inheritance/AppUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/inheritance/AppUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/ActressUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/ActressUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/ActressUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/ActressUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/CompositionUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/CompositionUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/CompositionUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/CompositionUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/InheritanceUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/InheritanceUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/InheritanceUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/InheritanceUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/PersonUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/PersonUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/PersonUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/PersonUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/WaitressUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/WaitressUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/inheritancecomposition/test/WaitressUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/inheritancecomposition/test/WaitressUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/initializationguide/UserUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/initializationguide/UserUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/initializationguide/UserUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/initializationguide/UserUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverloadingUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverloadingUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverloadingUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverloadingUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverridingUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverridingUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverridingUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/methodoverloadingoverriding/test/MethodOverridingUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java b/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java b/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java b/core-java-lang-oop/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/typeerasure/TypeErasureUnitTest.java diff --git a/core-java-lang-oop/src/test/resources/.gitignore b/core-java-lang-oop/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-lang-oop/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java-lang-syntax/.gitignore b/core-java-lang-syntax/.gitignore new file mode 100644 index 0000000000..374c8bf907 --- /dev/null +++ b/core-java-lang-syntax/.gitignore @@ -0,0 +1,25 @@ +*.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 +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-lang-syntax/README.md b/core-java-lang-syntax/README.md new file mode 100644 index 0000000000..a7c1b7cc4a --- /dev/null +++ b/core-java-lang-syntax/README.md @@ -0,0 +1,19 @@ +========= + +## Core Java Lang Syntax Cookbooks and Examples + +### Relevant Articles: +- [Introduction to Java Generics](http://www.baeldung.com/java-generics) +- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions) +- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) +- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) +- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) +- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) +- [A Guide to Java Loops](http://www.baeldung.com/java-loops) +- [Varargs in Java](http://www.baeldung.com/java-varargs) +- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) +- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) +- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system) +- [Java Switch Statement](https://www.baeldung.com/java-switch) +- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java) +- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator) \ No newline at end of file diff --git a/core-java-lang-syntax/pom.xml b/core-java-lang-syntax/pom.xml new file mode 100644 index 0000000000..9481f29459 --- /dev/null +++ b/core-java-lang-syntax/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + com.baeldung + core-java-lang-syntax + 0.1.0-SNAPSHOT + jar + core-java-lang-syntax + + + 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 + + + + + core-java-lang-syntax + + + src/main/resources + true + + + + + + + 3.10.0 + + + diff --git a/core-java-lang/src/main/java/com/baeldung/breakcontinue/BreakContinue.java b/core-java-lang-syntax/src/main/java/com/baeldung/breakcontinue/BreakContinue.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/breakcontinue/BreakContinue.java rename to core-java-lang-syntax/src/main/java/com/baeldung/breakcontinue/BreakContinue.java diff --git a/core-java-lang/src/main/java/com/baeldung/enums/Pizza.java b/core-java-lang-syntax/src/main/java/com/baeldung/enums/Pizza.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/enums/Pizza.java rename to core-java-lang-syntax/src/main/java/com/baeldung/enums/Pizza.java diff --git a/core-java-lang/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java-lang-syntax/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java rename to core-java-lang-syntax/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java diff --git a/core-java-lang/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java-lang-syntax/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java rename to core-java-lang-syntax/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java diff --git a/core-java-lang/src/main/java/com/baeldung/enums/README.md b/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/enums/README.md rename to core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md diff --git a/core-java-lang/src/main/java/com/baeldung/generics/Building.java b/core-java-lang-syntax/src/main/java/com/baeldung/generics/Building.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/generics/Building.java rename to core-java-lang-syntax/src/main/java/com/baeldung/generics/Building.java diff --git a/core-java-lang/src/main/java/com/baeldung/generics/Generics.java b/core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/generics/Generics.java rename to core-java-lang-syntax/src/main/java/com/baeldung/generics/Generics.java diff --git a/core-java-lang/src/main/java/com/baeldung/generics/House.java b/core-java-lang-syntax/src/main/java/com/baeldung/generics/House.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/generics/House.java rename to core-java-lang-syntax/src/main/java/com/baeldung/generics/House.java diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/initializationguide/User.java b/core-java-lang-syntax/src/main/java/com/baeldung/initializationguide/User.java new file mode 100644 index 0000000000..e2e3f051dd --- /dev/null +++ b/core-java-lang-syntax/src/main/java/com/baeldung/initializationguide/User.java @@ -0,0 +1,53 @@ +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-lang/src/main/java/com/baeldung/loops/InfiniteLoops.java b/core-java-lang-syntax/src/main/java/com/baeldung/loops/InfiniteLoops.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/loops/InfiniteLoops.java rename to core-java-lang-syntax/src/main/java/com/baeldung/loops/InfiniteLoops.java diff --git a/core-java-lang/src/main/java/com/baeldung/loops/LoopsInJava.java b/core-java-lang-syntax/src/main/java/com/baeldung/loops/LoopsInJava.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/loops/LoopsInJava.java rename to core-java-lang-syntax/src/main/java/com/baeldung/loops/LoopsInJava.java diff --git a/core-java-lang/src/main/java/com/baeldung/switchstatement/SwitchStatement.java b/core-java-lang-syntax/src/main/java/com/baeldung/switchstatement/SwitchStatement.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/switchstatement/SwitchStatement.java rename to core-java-lang-syntax/src/main/java/com/baeldung/switchstatement/SwitchStatement.java diff --git a/core-java-lang/src/main/java/com/baeldung/system/ChatWindow.java b/core-java-lang-syntax/src/main/java/com/baeldung/system/ChatWindow.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/system/ChatWindow.java rename to core-java-lang-syntax/src/main/java/com/baeldung/system/ChatWindow.java diff --git a/core-java-lang/src/main/java/com/baeldung/system/DateTimeService.java b/core-java-lang-syntax/src/main/java/com/baeldung/system/DateTimeService.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/system/DateTimeService.java rename to core-java-lang-syntax/src/main/java/com/baeldung/system/DateTimeService.java diff --git a/core-java-lang/src/main/java/com/baeldung/system/EnvironmentVariables.java b/core-java-lang-syntax/src/main/java/com/baeldung/system/EnvironmentVariables.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/system/EnvironmentVariables.java rename to core-java-lang-syntax/src/main/java/com/baeldung/system/EnvironmentVariables.java diff --git a/core-java-lang/src/main/java/com/baeldung/system/SystemErrDemo.java b/core-java-lang-syntax/src/main/java/com/baeldung/system/SystemErrDemo.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/system/SystemErrDemo.java rename to core-java-lang-syntax/src/main/java/com/baeldung/system/SystemErrDemo.java diff --git a/core-java-lang/src/main/java/com/baeldung/system/SystemExitDemo.java b/core-java-lang-syntax/src/main/java/com/baeldung/system/SystemExitDemo.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/system/SystemExitDemo.java rename to core-java-lang-syntax/src/main/java/com/baeldung/system/SystemExitDemo.java diff --git a/core-java-lang/src/main/java/com/baeldung/system/SystemOutDemo.java b/core-java-lang-syntax/src/main/java/com/baeldung/system/SystemOutDemo.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/system/SystemOutDemo.java rename to core-java-lang-syntax/src/main/java/com/baeldung/system/SystemOutDemo.java diff --git a/core-java-lang/src/main/java/com/baeldung/system/UserCredentials.java b/core-java-lang-syntax/src/main/java/com/baeldung/system/UserCredentials.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/system/UserCredentials.java rename to core-java-lang-syntax/src/main/java/com/baeldung/system/UserCredentials.java diff --git a/core-java-lang/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/enums/PizzaUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/enums/PizzaUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/enums/PizzaUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/generics/GenericsUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/generics/GenericsUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/generics/GenericsUnitTest.java diff --git a/core-java-lang-syntax/src/test/java/com/baeldung/initializationguide/UserUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/initializationguide/UserUnitTest.java new file mode 100644 index 0000000000..f74384e6f7 --- /dev/null +++ b/core-java-lang-syntax/src/test/java/com/baeldung/initializationguide/UserUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.initializationguide; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.*; + +import java.lang.reflect.InvocationTargetException; + +public class UserUnitTest { + + @Test + public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() { + User user = new User("Alice", 1); + assertThat(user).isNotNull(); + } + + @Test + public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + User user = User.class.getConstructor(String.class, int.class) + .newInstance("Alice", 2); + assertThat(user).isNotNull(); + } + + @Test + public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException { + User user = new User("Alice", 3); + User clonedUser = (User) user.clone(); + assertThat(clonedUser).isEqualTo(user); + } + + @Test + public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() { + User user = new User(); + assertThat(user.getName()).isNull(); + assertThat(user.getId() == 0); + } +} diff --git a/core-java-lang/src/test/java/com/baeldung/java/diamond/Car.java b/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Car.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/java/diamond/Car.java rename to core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Car.java diff --git a/core-java-lang/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/DiamondOperatorUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/java/diamond/Diesel.java b/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Diesel.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/java/diamond/Diesel.java rename to core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Diesel.java diff --git a/core-java-lang/src/test/java/com/baeldung/java/diamond/Engine.java b/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Engine.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/java/diamond/Engine.java rename to core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Engine.java diff --git a/core-java-lang/src/test/java/com/baeldung/java/diamond/Vehicle.java b/core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Vehicle.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/java/diamond/Vehicle.java rename to core-java-lang-syntax/src/test/java/com/baeldung/java/diamond/Vehicle.java diff --git a/core-java-lang/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/java/doublebrace/DoubleBraceUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/loops/WhenUsingLoops.java b/core-java-lang-syntax/src/test/java/com/baeldung/loops/WhenUsingLoops.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/loops/WhenUsingLoops.java rename to core-java-lang-syntax/src/test/java/com/baeldung/loops/WhenUsingLoops.java diff --git a/core-java-lang/src/test/java/com/baeldung/modulo/ModuloUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/modulo/ModuloUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/modulo/ModuloUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/modulo/ModuloUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/primitiveconversion/PrimitiveConversionsJUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/primitiveconversion/PrimitiveConversionsJUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/primitiveconversion/PrimitiveConversionsJUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/primitiveconversion/PrimitiveConversionsJUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/switchstatement/SwitchStatementUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/system/SystemNanoUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/system/SystemNanoUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/system/SystemNanoUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/system/SystemNanoUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/varargs/FormatterUnitTest.java b/core-java-lang-syntax/src/test/java/com/baeldung/varargs/FormatterUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/varargs/FormatterUnitTest.java rename to core-java-lang-syntax/src/test/java/com/baeldung/varargs/FormatterUnitTest.java diff --git a/core-java-lang/README.md b/core-java-lang/README.md index 85312cba68..52dfe708a3 100644 --- a/core-java-lang/README.md +++ b/core-java-lang/README.md @@ -4,44 +4,24 @@ ### Relevant Articles: - [Guide to Java Reflection](http://www.baeldung.com/java-reflection) -- [Introduction to Java Generics](http://www.baeldung.com/java-generics) - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) - [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions) -- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions) - [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection) - [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration) - [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) - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) -- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) -- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) - [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable) - [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) -- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization) - [Nested Classes in Java](http://www.baeldung.com/java-nested-classes) -- [A Guide to Java Loops](http://www.baeldung.com/java-loops) -- [Varargs in Java](http://www.baeldung.com/java-varargs) - [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces) -- [Polymorphism in Java](http://www.baeldung.com/java-polymorphism) - [Recursion In Java](http://www.baeldung.com/java-recursion) - [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize) -- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override) -- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy) -- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance) -- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting) -- [The "final" Keyword in Java](http://www.baeldung.com/java-final) - [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) - [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system) -- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure) - [Using Java Assertions](http://www.baeldung.com/java-assert) -- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) -- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding) -- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers) -- [Guide to the super Java Keyword](http://www.baeldung.com/java-super) -- [Guide to the this Java Keyword](http://www.baeldung.com/java-this) -- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object) - [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror) - [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error) - [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception) @@ -50,10 +30,6 @@ - [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding) - [Difference Between Throw and Throws in Java](https://www.baeldung.com/java-throw-throws) - [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic) -- [Java Switch Statement](https://www.baeldung.com/java-switch) -- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java) -- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator) - [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts) - [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws) -- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - +- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name) diff --git a/core-java-lang/native/nativedatetimeutils.dll b/core-java-lang/native/nativedatetimeutils.dll new file mode 100644 index 0000000000..ecdd388380 Binary files /dev/null and b/core-java-lang/native/nativedatetimeutils.dll differ diff --git a/core-java-lang/pom.xml b/core-java-lang/pom.xml index ace39de274..283acab775 100644 --- a/core-java-lang/pom.xml +++ b/core-java-lang/pom.xml @@ -56,11 +56,6 @@ ${assertj-core.version} test - - org.springframework - spring-web - ${springframework.spring-web.version} - javax.mail mail @@ -76,334 +71,12 @@ true - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - - 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 - - - - - - - - - - - 2.8.5 + 2.9.7 2.8.2 @@ -414,16 +87,6 @@ 3.10.0 - - - 2.21.0 - 4.3.4.RELEASE - 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-lang/src/main/java/com/baeldung/className/RetrievingClassName.java b/core-java-lang/src/main/java/com/baeldung/className/RetrievingClassName.java new file mode 100644 index 0000000000..ab6c8a51ff --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/className/RetrievingClassName.java @@ -0,0 +1,9 @@ +package com.baeldung.className; + +public class RetrievingClassName { + + public class InnerClass { + + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/controlstructures/ConditionalBranches.java b/core-java-lang/src/main/java/com/baeldung/controlstructures/ConditionalBranches.java new file mode 100644 index 0000000000..bace609699 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/controlstructures/ConditionalBranches.java @@ -0,0 +1,68 @@ +package com.baeldung.controlstructures; + +public class ConditionalBranches { + + /** + * Multiple if/else/else if statements examples. Shows different syntax usage. + */ + public static void ifElseStatementsExamples() { + int count = 2; // Initial count value. + + // Basic syntax. Only one statement follows. No brace usage. + if (count > 1) + System.out.println("Count is higher than 1"); + + // Basic syntax. More than one statement can be included. Braces are used (recommended syntax). + if (count > 1) { + System.out.println("Count is higher than 1"); + System.out.println("Count is equal to: " + count); + } + + // If/Else syntax. Two different courses of action can be included. + if (count > 2) { + System.out.println("Count is higher than 2"); + } else { + System.out.println("Count is lower or equal than 2"); + } + + // If/Else/Else If syntax. Three or more courses of action can be included. + if (count > 2) { + System.out.println("Count is higher than 2"); + } else if (count <= 0) { + System.out.println("Count is less or equal than zero"); + } else { + System.out.println("Count is either equal to one, or two"); + } + } + + /** + * Ternary Operator example. + * @see ConditionalBranches#ifElseStatementsExamples() + */ + public static void ternaryExample() { + int count = 2; + System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2"); + } + + /** + * Switch structure example. Shows how to replace multiple if/else statements with one structure. + */ + public static void switchExample() { + int count = 3; + switch (count) { + case 0: + System.out.println("Count is equal to 0"); + break; + case 1: + System.out.println("Count is equal to 1"); + break; + case 2: + System.out.println("Count is equal to 2"); + break; + default: + System.out.println("Count is either negative, or higher than 2"); + break; + } + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java b/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java new file mode 100644 index 0000000000..bc4515bfc7 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java @@ -0,0 +1,157 @@ +package com.baeldung.controlstructures; + +public class Loops { + + /** + * Dummy method. Only prints a generic message. + */ + private static void methodToRepeat() { + System.out.println("Dummy method."); + } + + /** + * Shows how to iterate 50 times with 3 different method/control structures. + */ + public static void repetitionTo50Examples() { + for (int i = 1; i <= 50; i++) { + methodToRepeat(); + } + + int whileCounter = 1; + while (whileCounter <= 50) { + methodToRepeat(); + whileCounter++; + } + + int count = 1; + do { + methodToRepeat(); + count++; + } while (count < 50); + } + + /** + * Splits a sentence in words, and prints each word in a new line. + * @param sentence Sentence to print as independent words. + */ + public static void printWordByWord(String sentence) { + for (String word : sentence.split(" ")) { + System.out.println(word); + } + } + + /** + * Prints text an N amount of times. Shows usage of the {@code break} branching statement. + * @param textToPrint Text to repeatedly print. + * @param times Amount to times to print received text. + */ + public static void printTextNTimes(String textToPrint, int times) { + int counter = 1; + while (true) { + System.out.println(textToPrint); + if (counter == times) { + break; + } + } + } + + /** + * Prints text an N amount of times, up to 50. Shows usage of the {@code break} branching statement. + * @param textToPrint Text to repeatedly print. + * @param times Amount to times to print received text. If times is higher than 50, textToPrint will only be printed 50 times. + */ + public static void printTextNTimesUpTo50(String textToPrint, int times) { + int counter = 1; + while (counter < 50) { + System.out.println(textToPrint); + if (counter == times) { + break; + } + } + } + + /** + * Finds the index of {@code name} in a list + * @param name The name to look for + * @param names The list of names + * @return The index where the name was found or -1 otherwise + */ + public static int findFirstInstanceOfName(String name, String[] names) { + int index = 0; + for ( ; index < names.length; index++) { + if (names[index].equals(name)) { + break; + } + } + return index == names.length ? -1 : index; + } + + /** + * Takes several names and makes a list, skipping the specified {@code name}. + * + * @param name The name to skip + * @param names The list of names + * @return The list of names as a single string, missing the specified {@code name}. + */ + public static String makeListSkippingName(String name, String[] names) { + String list = ""; + for (int i = 0; i < names.length; i++) { + if (names[i].equals(name)) { + continue; + } + list += names[i]; + } + return list; + } + + /** + * Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements. + * @param amountToPrint Amount of even numbers to print. + */ + public static void printEvenNumbers(int amountToPrint) { + if (amountToPrint <= 0) { // Invalid input + return; + } + int iterator = 0; + int amountPrinted = 0; + while (true) { + if (iterator % 2 == 0) { // Is an even number + System.out.println(iterator); + amountPrinted++; + iterator++; + } else { + iterator++; + continue; // Won't print + } + if (amountPrinted == amountToPrint) { + break; + } + } + } + + /** + * Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements. + * @param amountToPrint Amount of even numbers to print. + */ + public static void printEvenNumbersToAMaxOf100(int amountToPrint) { + if (amountToPrint <= 0) { // Invalid input + return; + } + int iterator = 0; + int amountPrinted = 0; + while (amountPrinted < 100) { + if (iterator % 2 == 0) { // Is an even number + System.out.println(iterator); + amountPrinted++; + iterator++; + } else { + iterator++; + continue; // Won't print + } + if (amountPrinted == amountToPrint) { + break; + } + } + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/nativekeyword/DateTimeUtils.java b/core-java-lang/src/main/java/com/baeldung/nativekeyword/DateTimeUtils.java new file mode 100644 index 0000000000..0762b0eb8a --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/nativekeyword/DateTimeUtils.java @@ -0,0 +1,10 @@ +package com.baeldung.nativekeyword; + +public class DateTimeUtils { + + public native String getSystemTime(); + + static { + System.loadLibrary("nativedatetimeutils"); + } +} diff --git a/core-java-lang/src/main/java/com/baeldung/nativekeyword/NativeMainApp.java b/core-java-lang/src/main/java/com/baeldung/nativekeyword/NativeMainApp.java new file mode 100644 index 0000000000..76fe548ed3 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/nativekeyword/NativeMainApp.java @@ -0,0 +1,11 @@ +package com.baeldung.nativekeyword; + +import com.baeldung.nativekeyword.DateTimeUtils; + +public class NativeMainApp { + public static void main(String[] args) { + DateTimeUtils dateTimeUtils = new DateTimeUtils(); + String input = dateTimeUtils.getSystemTime(); + System.out.println("System time is : " + input); + } +} diff --git a/core-java-lang/src/main/java/com/baeldung/packages/TodoApp.java b/core-java-lang/src/main/java/com/baeldung/packages/TodoApp.java new file mode 100644 index 0000000000..0f4a56f708 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/TodoApp.java @@ -0,0 +1,22 @@ +package com.baeldung.packages; + +import java.time.LocalDate; + +import com.baeldung.packages.domain.TodoItem; + +public class TodoApp { + + public static void main(String[] args) { + TodoList todoList = new TodoList(); + for (int i = 0; i < 3; i++) { + TodoItem item = new TodoItem(); + item.setId(Long.valueOf((long)i)); + item.setDescription("Todo item " + (i + 1)); + item.setDueDate(LocalDate.now().plusDays((long)(i + 1))); + todoList.addTodoItem(item); + } + + todoList.getTodoItems().forEach((TodoItem todoItem) -> System.out.println(todoItem.toString())); + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java b/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java new file mode 100644 index 0000000000..6ed6cd4ec1 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java @@ -0,0 +1,27 @@ +package com.baeldung.packages; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.packages.domain.TodoItem; + +public class TodoList { + private List todoItems; + + public void addTodoItem(TodoItem todoItem) { + if (todoItems == null) { + todoItems = new ArrayList(); + } + + todoItems.add(todoItem); + } + + public List getTodoItems() { + return todoItems; + } + + public void setTodoItems(List todoItems) { + this.todoItems = todoItems; + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java b/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java new file mode 100644 index 0000000000..972e574a7f --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java @@ -0,0 +1,39 @@ +package com.baeldung.packages.domain; + +import java.time.LocalDate; + +public class TodoItem { + private Long id; + private String description; + private LocalDate dueDate; + + 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; + } + + public LocalDate getDueDate() { + return dueDate; + } + + public void setDueDate(LocalDate dueDate) { + this.dueDate = dueDate; + } + + @Override + public String toString() { + return "TodoItem [id=" + id + ", description=" + description + ", dueDate=" + dueDate + "]"; + } + +} diff --git a/core-java-lang/src/test/java/com/baeldung/className/RetrievingClassNameUnitTest.java b/core-java-lang/src/test/java/com/baeldung/className/RetrievingClassNameUnitTest.java new file mode 100644 index 0000000000..f9dbf91d2c --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/className/RetrievingClassNameUnitTest.java @@ -0,0 +1,156 @@ +package com.baeldung.className; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class RetrievingClassNameUnitTest { + + // Retrieving Simple Name + @Test + public void givenRetrievingClassName_whenGetSimpleName_thenRetrievingClassName() { + assertEquals("RetrievingClassName", RetrievingClassName.class.getSimpleName()); + } + + @Test + public void givenPrimitiveInt_whenGetSimpleName_thenInt() { + assertEquals("int", int.class.getSimpleName()); + } + + @Test + public void givenRetrievingClassNameArray_whenGetSimpleName_thenRetrievingClassNameWithBrackets() { + assertEquals("RetrievingClassName[]", RetrievingClassName[].class.getSimpleName()); + assertEquals("RetrievingClassName[][]", RetrievingClassName[][].class.getSimpleName()); + } + + @Test + public void givenAnonymousClass_whenGetSimpleName_thenEmptyString() { + assertEquals("", new RetrievingClassName() {}.getClass().getSimpleName()); + } + + // Retrieving Other Names + // - Primitive Types + @Test + public void givenPrimitiveInt_whenGetName_thenInt() { + assertEquals("int", int.class.getName()); + } + + @Test + public void givenPrimitiveInt_whenGetTypeName_thenInt() { + assertEquals("int", int.class.getTypeName()); + } + + @Test + public void givenPrimitiveInt_whenGetCanonicalName_thenInt() { + assertEquals("int", int.class.getCanonicalName()); + } + + // - Object Types + @Test + public void givenRetrievingClassName_whenGetName_thenCanonicalName() { + assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getName()); + } + + @Test + public void givenRetrievingClassName_whenGetTypeName_thenCanonicalName() { + assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getTypeName()); + } + + @Test + public void givenRetrievingClassName_whenGetCanonicalName_thenCanonicalName() { + assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getCanonicalName()); + } + + // - Inner Classes + @Test + public void givenRetrievingClassNameInnerClass_whenGetName_thenCanonicalNameWithDollarSeparator() { + assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getName()); + } + + @Test + public void givenRetrievingClassNameInnerClass_whenGetTypeName_thenCanonicalNameWithDollarSeparator() { + assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getTypeName()); + } + + @Test + public void givenRetrievingClassNameInnerClass_whenGetCanonicalName_thenCanonicalName() { + assertEquals("com.baeldung.className.RetrievingClassName.InnerClass", RetrievingClassName.InnerClass.class.getCanonicalName()); + } + + // - Anonymous Classes + @Test + public void givenAnonymousClass_whenGetName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() { + // These are the second and third appearences of an anonymous class in RetrievingClassNameUnitTest, hence $2 and $3 expectations + assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$2", new RetrievingClassName() {}.getClass().getName()); + assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$3", new RetrievingClassName() {}.getClass().getName()); + } + + @Test + public void givenAnonymousClass_whenGetTypeName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() { + // These are the fourth and fifth appearences of an anonymous class in RetrievingClassNameUnitTest, hence $4 and $5 expectations + assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$4", new RetrievingClassName() {}.getClass().getTypeName()); + assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$5", new RetrievingClassName() {}.getClass().getTypeName()); + } + + @Test + public void givenAnonymousClass_whenGetCanonicalName_thenNull() { + assertNull(new RetrievingClassName() {}.getClass().getCanonicalName()); + } + + // - Arrays + @Test + public void givenPrimitiveIntArray_whenGetName_thenOpeningBracketsAndPrimitiveIntLetter() { + assertEquals("[I", int[].class.getName()); + assertEquals("[[I", int[][].class.getName()); + } + + @Test + public void givenRetrievingClassNameArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameGetName() { + assertEquals("[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[].class.getName()); + assertEquals("[[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[][].class.getName()); + } + + @Test + public void givenRetrievingClassNameInnerClassArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameInnerClassGetName() { + assertEquals("[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[].class.getName()); + assertEquals("[[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[][].class.getName()); + } + + @Test + public void givenPrimitiveIntArray_whenGetTypeName_thenPrimitiveIntGetTypeNameWithBrackets() { + assertEquals("int[]", int[].class.getTypeName()); + assertEquals("int[][]", int[][].class.getTypeName()); + } + + @Test + public void givenRetrievingClassNameArray_whenGetTypeName_thenRetrievingClassNameGetTypeNameWithBrackets() { + assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getTypeName()); + assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getTypeName()); + } + + @Test + public void givenRetrievingClassNameInnerClassArray_whenGetTypeName_thenRetrievingClassNameInnerClassGetTypeNameWithBrackets() { + assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[]", RetrievingClassName.InnerClass[].class.getTypeName()); + assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[][]", RetrievingClassName.InnerClass[][].class.getTypeName()); + } + + @Test + public void givenPrimitiveIntArray_whenGetCanonicalName_thenPrimitiveIntGetCanonicalNameWithBrackets() { + assertEquals("int[]", int[].class.getCanonicalName()); + assertEquals("int[][]", int[][].class.getCanonicalName()); + } + + @Test + public void givenRetrievingClassNameArray_whenGetCanonicalName_thenRetrievingClassNameGetCanonicalNameWithBrackets() { + assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getCanonicalName()); + assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getCanonicalName()); + } + + @Test + public void givenRetrievingClassNameInnerClassArray_whenGetCanonicalName_thenRetrievingClassNameInnerClassGetCanonicalNameWithBrackets() { + assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[]", RetrievingClassName.InnerClass[].class.getCanonicalName()); + assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[][]", RetrievingClassName.InnerClass[][].class.getCanonicalName()); + } + +} \ No newline at end of file diff --git a/core-java-lang/src/test/java/com/baeldung/compoundoperators/CompoundOperatorsUnitTest.java b/core-java-lang/src/test/java/com/baeldung/compoundoperators/CompoundOperatorsUnitTest.java new file mode 100644 index 0000000000..532776edd4 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/compoundoperators/CompoundOperatorsUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.compoundoperators; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CompoundOperatorsUnitTest { + + @Test + public void whenAssignmentOperatorIsUsed_thenValueIsAssigned() { + int x = 5; + + assertEquals(5, x); + } + + @Test + public void whenCompoundAssignmentUsed_thenSameAsSimpleAssignment() { + int a = 3, b = 3, c = -2; + a = a * c; // Simple assignment operator + b *= c; // Compound assignment operator + + assertEquals(a, b); + } + + @Test + public void whenAssignmentOperatorIsUsed_thenValueIsReturned() { + long x = 1; + long y = (x+=2); + + assertEquals(3, y); + assertEquals(y, x); + } + + @Test + public void whenCompoundOperatorsAreUsed_thenOperationsArePerformedAndAssigned() { + //Simple assignment + int x = 5; //x is 5 + + //Incrementation + x += 5; //x is 10 + assertEquals(10, x); + + //Decrementation + x -= 2; //x is 8 + assertEquals(8, x); + + //Multiplication + x *= 2; //x is 16 + assertEquals(16, x); + + //Division + x /= 4; //x is 4 + assertEquals(4, x); + + //Modulus + x %= 3; //x is 1 + assertEquals(1, x); + + + //Binary AND + x &= 4; //x is 0 + assertEquals(0, x); + + //Binary exclusive OR + x ^= 4; //x is 4 + assertEquals(4, x); + + //Binary inclusive OR + x |= 8; //x is 12 + assertEquals(12, x); + + + //Binary Left Shift + x <<= 2; //x is 48 + assertEquals(48, x); + + //Binary Right Shift + x >>= 2; //x is 12 + assertEquals(12, x); + + //Shift right zero fill + x >>>= 1; //x is 6 + assertEquals(6, x); + } + + @Test(expected = NullPointerException.class) + public void whenArrayIsNull_thenThrowNullException() { + int[] numbers = null; + + //Trying Incrementation + numbers[2] += 5; + } + + @Test(expected = ArrayIndexOutOfBoundsException.class) + public void whenArrayIndexNotCorrect_thenThrowArrayIndexException() { + int[] numbers = {0, 1}; + + //Trying Incrementation + numbers[2] += 5; + } + + @Test + public void whenArrayIndexIsCorrect_thenPerformOperation() { + int[] numbers = {0, 1}; + + //Incrementation + numbers[1] += 5; + assertEquals(6, numbers[1]); + } + +} diff --git a/core-java-lang/src/test/java/com/baeldung/nativekeyword/DateTimeUtilsManualTest.java b/core-java-lang/src/test/java/com/baeldung/nativekeyword/DateTimeUtilsManualTest.java new file mode 100644 index 0000000000..d5003dfc1f --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/nativekeyword/DateTimeUtilsManualTest.java @@ -0,0 +1,27 @@ +package com.baeldung.nativekeyword; + +import static org.junit.Assert.assertNotNull; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; + +public class DateTimeUtilsManualTest { + + private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(DateTimeUtilsManualTest.class); + + @BeforeClass + public static void setUpClass() { + System.loadLibrary("msvcr100"); + System.loadLibrary("libgcc_s_sjlj-1"); + System.loadLibrary("libstdc++-6"); + System.loadLibrary("nativedatetimeutils"); + } + + @Test + public void givenNativeLibsLoaded_thenNativeMethodIsAccessible() { + DateTimeUtils dateTimeUtils = new DateTimeUtils(); + LOG.info("System time is : " + dateTimeUtils.getSystemTime()); + assertNotNull(dateTimeUtils.getSystemTime()); + } +} diff --git a/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java b/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java new file mode 100644 index 0000000000..212fb7b3c7 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.packages; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; + +import org.junit.Test; + +import com.baeldung.packages.domain.TodoItem; + +public class PackagesUnitTest { + + @Test + public void whenTodoItemAdded_ThenSizeIncreases() { + TodoItem todoItem = new TodoItem(); + todoItem.setId(1L); + todoItem.setDescription("Test the Todo List"); + todoItem.setDueDate(LocalDate.now()); + TodoList todoList = new TodoList(); + todoList.addTodoItem(todoItem); + assertEquals(1, todoList.getTodoItems().size()); + } +} diff --git a/core-java-networking/.gitignore b/core-java-networking/.gitignore new file mode 100644 index 0000000000..374c8bf907 --- /dev/null +++ b/core-java-networking/.gitignore @@ -0,0 +1,25 @@ +*.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 +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-networking/README.md b/core-java-networking/README.md new file mode 100644 index 0000000000..b2367782b6 --- /dev/null +++ b/core-java-networking/README.md @@ -0,0 +1,16 @@ +========= + +## Core Java Networking + +### Relevant Articles + +- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server) +- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast) +- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java) +- [Sending Emails with Java](http://www.baeldung.com/java-email) +- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java) +- [A Guide to the Java URL](http://www.baeldung.com/java-url) +- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) +- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) +- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding) +- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) \ No newline at end of file diff --git a/core-java-networking/pom.xml b/core-java-networking/pom.xml new file mode 100644 index 0000000000..d9c7c691e9 --- /dev/null +++ b/core-java-networking/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + core-java-networking + 0.1.0-SNAPSHOT + jar + core-java-networking + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + javax.mail + mail + ${javax.mail.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.springframework + spring-web + ${springframework.spring-web.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + core-java-networking + + + + 1.5.0-b01 + 2.5 + 3.5 + 4.3.4.RELEASE + + diff --git a/core-java-networking/src/main/java/com/baeldung/http/FullResponseBuilder.java b/core-java-networking/src/main/java/com/baeldung/http/FullResponseBuilder.java new file mode 100644 index 0000000000..394255bd70 --- /dev/null +++ b/core-java-networking/src/main/java/com/baeldung/http/FullResponseBuilder.java @@ -0,0 +1,65 @@ +package com.baeldung.http; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.HttpURLConnection; +import java.util.Iterator; +import java.util.List; + +public class FullResponseBuilder { + public static String getFullResponse(HttpURLConnection con) throws IOException { + StringBuilder fullResponseBuilder = new StringBuilder(); + + fullResponseBuilder.append(con.getResponseCode()) + .append(" ") + .append(con.getResponseMessage()) + .append("\n"); + + con.getHeaderFields() + .entrySet() + .stream() + .filter(entry -> entry.getKey() != null) + .forEach(entry -> { + + fullResponseBuilder.append(entry.getKey()) + .append(": "); + + List headerValues = entry.getValue(); + Iterator it = headerValues.iterator(); + if (it.hasNext()) { + fullResponseBuilder.append(it.next()); + + while (it.hasNext()) { + fullResponseBuilder.append(", ") + .append(it.next()); + } + } + + fullResponseBuilder.append("\n"); + }); + + Reader streamReader = null; + + if (con.getResponseCode() > 299) { + streamReader = new InputStreamReader(con.getErrorStream()); + } else { + streamReader = new InputStreamReader(con.getInputStream()); + } + + BufferedReader in = new BufferedReader(streamReader); + String inputLine; + StringBuilder content = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + + in.close(); + + fullResponseBuilder.append("Response: ") + .append(content); + + return fullResponseBuilder.toString(); + } +} diff --git a/core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java b/core-java-networking/src/main/java/com/baeldung/http/ParameterStringBuilder.java similarity index 100% rename from core-java/src/main/java/com/baeldung/http/ParameterStringBuilder.java rename to core-java-networking/src/main/java/com/baeldung/http/ParameterStringBuilder.java diff --git a/core-java/src/main/java/com/baeldung/mail/EmailService.java b/core-java-networking/src/main/java/com/baeldung/mail/EmailService.java similarity index 100% rename from core-java/src/main/java/com/baeldung/mail/EmailService.java rename to core-java-networking/src/main/java/com/baeldung/mail/EmailService.java diff --git a/core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java b/core-java-networking/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java rename to core-java-networking/src/main/java/com/baeldung/networking/cookies/PersistentCookieStore.java diff --git a/core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java-networking/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java rename to core-java-networking/src/main/java/com/baeldung/networking/cookies/ProxyAcceptCookiePolicy.java diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java diff --git a/core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java b/core-java-networking/src/main/java/com/baeldung/networking/udp/EchoClient.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/udp/EchoClient.java rename to core-java-networking/src/main/java/com/baeldung/networking/udp/EchoClient.java diff --git a/core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java b/core-java-networking/src/main/java/com/baeldung/networking/udp/EchoServer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/udp/EchoServer.java rename to core-java-networking/src/main/java/com/baeldung/networking/udp/EchoServer.java diff --git a/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java b/core-java-networking/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java rename to core-java-networking/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingClient.java diff --git a/core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java b/core-java-networking/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java rename to core-java-networking/src/main/java/com/baeldung/networking/udp/broadcast/BroadcastingEchoServer.java diff --git a/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java b/core-java-networking/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java rename to core-java-networking/src/main/java/com/baeldung/networking/udp/multicast/MulticastEchoServer.java diff --git a/core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java b/core-java-networking/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java similarity index 100% rename from core-java/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java rename to core-java-networking/src/main/java/com/baeldung/networking/udp/multicast/MulticastingClient.java diff --git a/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URIDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/uriurl/URIDemo.java similarity index 98% rename from core-java/src/main/java/com/baeldung/javanetworking/uriurl/URIDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/uriurl/URIDemo.java index 121e0f5d72..91f6e21293 100644 --- a/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URIDemo.java +++ b/core-java-networking/src/main/java/com/baeldung/networking/uriurl/URIDemo.java @@ -1,4 +1,4 @@ -package com.baeldung.javanetworking.uriurl; +package com.baeldung.networking.uriurl; import java.io.BufferedReader; import java.io.IOException; diff --git a/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URLDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/uriurl/URLDemo.java similarity index 98% rename from core-java/src/main/java/com/baeldung/javanetworking/uriurl/URLDemo.java rename to core-java-networking/src/main/java/com/baeldung/networking/uriurl/URLDemo.java index 109a9951d2..d257e7a295 100644 --- a/core-java/src/main/java/com/baeldung/javanetworking/uriurl/URLDemo.java +++ b/core-java-networking/src/main/java/com/baeldung/networking/uriurl/URLDemo.java @@ -1,4 +1,4 @@ -package com.baeldung.javanetworking.uriurl; +package com.baeldung.networking.uriurl; import java.io.BufferedReader; import java.io.IOException; diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java-networking/src/main/java/com/baeldung/socket/EchoClient.java similarity index 100% rename from core-java/src/main/java/com/baeldung/socket/EchoClient.java rename to core-java-networking/src/main/java/com/baeldung/socket/EchoClient.java diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java-networking/src/main/java/com/baeldung/socket/EchoMultiServer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java rename to core-java-networking/src/main/java/com/baeldung/socket/EchoMultiServer.java diff --git a/core-java/src/main/java/com/baeldung/socket/EchoServer.java b/core-java-networking/src/main/java/com/baeldung/socket/EchoServer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/socket/EchoServer.java rename to core-java-networking/src/main/java/com/baeldung/socket/EchoServer.java diff --git a/core-java/src/main/java/com/baeldung/socket/GreetClient.java b/core-java-networking/src/main/java/com/baeldung/socket/GreetClient.java similarity index 100% rename from core-java/src/main/java/com/baeldung/socket/GreetClient.java rename to core-java-networking/src/main/java/com/baeldung/socket/GreetClient.java diff --git a/core-java/src/main/java/com/baeldung/socket/GreetServer.java b/core-java-networking/src/main/java/com/baeldung/socket/GreetServer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/socket/GreetServer.java rename to core-java-networking/src/main/java/com/baeldung/socket/GreetServer.java diff --git a/spring-rest-embedded-tomcat/src/main/resources/logback.xml b/core-java-networking/src/main/resources/logback.xml similarity index 57% rename from spring-rest-embedded-tomcat/src/main/resources/logback.xml rename to core-java-networking/src/main/resources/logback.xml index 7d900d8ea8..56af2d397e 100644 --- a/spring-rest-embedded-tomcat/src/main/resources/logback.xml +++ b/core-java-networking/src/main/resources/logback.xml @@ -7,6 +7,12 @@ + + + + + + diff --git a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java b/core-java-networking/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java rename to core-java-networking/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/http/HttpRequestLiveTest.java b/core-java-networking/src/test/java/com/baeldung/http/HttpRequestLiveTest.java similarity index 64% rename from core-java/src/test/java/com/baeldung/http/HttpRequestLiveTest.java rename to core-java-networking/src/test/java/com/baeldung/http/HttpRequestLiveTest.java index acd6536ac4..bd6c0a4410 100644 --- a/core-java/src/test/java/com/baeldung/http/HttpRequestLiveTest.java +++ b/core-java-networking/src/test/java/com/baeldung/http/HttpRequestLiveTest.java @@ -1,12 +1,13 @@ package com.baeldung.http; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.Test; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; +import java.io.Reader; import java.net.CookieManager; import java.net.HttpCookie; import java.net.HttpURLConnection; @@ -48,7 +49,8 @@ public class HttpRequestLiveTest { in.close(); assertEquals("status code incorrect", status, 200); - assertTrue("content incorrect", content.toString().contains("Example Domain")); + assertTrue("content incorrect", content.toString() + .contains("Example Domain")); } @Test @@ -89,18 +91,24 @@ public class HttpRequestLiveTest { Optional usernameCookie = null; if (cookiesHeader != null) { List cookies = HttpCookie.parse(cookiesHeader); - cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie)); - usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username")); + cookies.forEach(cookie -> cookieManager.getCookieStore() + .add(null, cookie)); + usernameCookie = cookies.stream() + .findAny() + .filter(cookie -> cookie.getName() + .equals("username")); } if (usernameCookie == null) { - cookieManager.getCookieStore().add(null, new HttpCookie("username", "john")); + cookieManager.getCookieStore() + .add(null, new HttpCookie("username", "john")); } con.disconnect(); con = (HttpURLConnection) url.openConnection(); - con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";")); + con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore() + .getCookies(), ";")); int status = con.getResponseCode(); @@ -125,4 +133,56 @@ public class HttpRequestLiveTest { assertEquals("status code incorrect", con.getResponseCode(), 200); } + @Test + public void whenFailedRequest_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + + con.setConnectTimeout(5000); + con.setReadTimeout(5000); + + int status = con.getResponseCode(); + + Reader streamReader = null; + + if (status > 299) { + streamReader = new InputStreamReader(con.getErrorStream()); + } else { + streamReader = new InputStreamReader(con.getInputStream()); + } + + BufferedReader in = new BufferedReader(streamReader); + String inputLine; + StringBuilder content = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + con.disconnect(); + + assertEquals("status code incorrect", status, 411); + assertTrue("error content", content.toString() + .contains("411 - Length Required")); + } + + @Test + public void whenGetRequestFullResponse_thenOk() throws IOException { + URL url = new URL("http://example.com"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + con.setConnectTimeout(5000); + con.setReadTimeout(5000); + + String fullResponse = FullResponseBuilder.getFullResponse(con); + + con.disconnect(); + + assertEquals("status code incorrect", con.getResponseCode(), 200); + assertTrue("header incorrect", fullResponse.contains("Content-Type: text/html; charset=UTF-8")); + assertTrue("response incorrect", fullResponse.contains("")); + } + } diff --git a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java b/core-java-networking/src/test/java/com/baeldung/networking/interfaces/NetworkInterfaceManualTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/interfaces/NetworkInterfaceManualTest.java index 8635a24f18..47a598f599 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java +++ b/core-java-networking/src/test/java/com/baeldung/networking/interfaces/NetworkInterfaceManualTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.interfaces; +package com.baeldung.networking.interfaces; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/networking/udp/UDPLiveTest.java b/core-java-networking/src/test/java/com/baeldung/networking/udp/UDPLiveTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/networking/udp/UDPLiveTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/udp/UDPLiveTest.java diff --git a/core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastLiveTest.java b/core-java-networking/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastLiveTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastLiveTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/udp/broadcast/BroadcastLiveTest.java diff --git a/core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastLiveTest.java b/core-java-networking/src/test/java/com/baeldung/networking/udp/multicast/MulticastLiveTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/networking/udp/multicast/MulticastLiveTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/udp/multicast/MulticastLiveTest.java diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java b/core-java-networking/src/test/java/com/baeldung/networking/uriurl/URIDemoLiveTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/uriurl/URIDemoLiveTest.java index 0c312ff613..3b73cc0943 100644 --- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java +++ b/core-java-networking/src/test/java/com/baeldung/networking/uriurl/URIDemoLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.javanetworking.uriurl.test; +package com.baeldung.networking.uriurl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -20,7 +20,7 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.baeldung.javanetworking.uriurl.URLDemo; +import com.baeldung.networking.uriurl.URLDemo; @FixMethodOrder public class URIDemoLiveTest { diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java b/core-java-networking/src/test/java/com/baeldung/networking/uriurl/URIvsURLUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/uriurl/URIvsURLUnitTest.java index 8837dc5556..ec1cb4c0c9 100644 --- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java +++ b/core-java-networking/src/test/java/com/baeldung/networking/uriurl/URIvsURLUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.javanetworking.uriurl; +package com.baeldung.networking.uriurl; import java.io.IOException; import java.net.MalformedURLException; diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java b/core-java-networking/src/test/java/com/baeldung/networking/uriurl/URLDemoLiveTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/uriurl/URLDemoLiveTest.java index 15f53ed878..a9104311e6 100644 --- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java +++ b/core-java-networking/src/test/java/com/baeldung/networking/uriurl/URLDemoLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.javanetworking.uriurl.test; +package com.baeldung.networking.uriurl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -18,7 +18,7 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.baeldung.javanetworking.uriurl.URLDemo; +import com.baeldung.networking.uriurl.URLDemo; @FixMethodOrder public class URLDemoLiveTest { diff --git a/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java b/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java rename to core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java index 505d9595ab..112f2cf53f 100644 --- a/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java +++ b/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.networking.url; +package com.baeldung.networking.url; import static org.junit.Assert.assertEquals; diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java-networking/src/test/java/com/baeldung/socket/EchoIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java rename to core-java-networking/src/test/java/com/baeldung/socket/EchoIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java b/core-java-networking/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java rename to core-java-networking/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java b/core-java-networking/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java rename to core-java-networking/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java diff --git a/core-java-networking/src/test/resources/.gitignore b/core-java-networking/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-networking/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java-perf/README.md b/core-java-perf/README.md new file mode 100644 index 0000000000..252ee4cc45 --- /dev/null +++ b/core-java-perf/README.md @@ -0,0 +1,8 @@ +## Core Java Performance + +### Relevant Articles: +- [Verbose Garbage Collection in Java](https://www.baeldung.com/java-verbose-gc) +- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture) +- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks) +- [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) \ No newline at end of file diff --git a/core-java-perf/pom.xml b/core-java-perf/pom.xml new file mode 100644 index 0000000000..062f76db77 --- /dev/null +++ b/core-java-perf/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.baeldung + core-java-perf + 0.1.0-SNAPSHOT + jar + core-java-perf + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + + + + 3.8.1 + + + + diff --git a/core-java-perf/src/main/java/com/baeldung/gc/VerboseGarbageCollectorRunner.java b/core-java-perf/src/main/java/com/baeldung/gc/VerboseGarbageCollectorRunner.java new file mode 100644 index 0000000000..f57580bbb5 --- /dev/null +++ b/core-java-perf/src/main/java/com/baeldung/gc/VerboseGarbageCollectorRunner.java @@ -0,0 +1,63 @@ +package com.baeldung.gc; + +import java.util.HashMap; +import java.util.Map; + +/** + * A simple Java program to demonstrate how to enable verbose Garbage Collection (GC) logging. + *

+ * This simple program loads 3 million {@link java.lang.String} instances into a {@link java.util.HashMap} + * object before making an explicit call to the garbage collector using System.gc(). + *

+ * Finally, it removes 2 million of the {@link java.lang.String} instances from the {@link java.util.HashMap}. + * We also explicitly use System.out.println to make interpreting the output easier. + *

+ * Run this program with the following arguments to see verbose GC logging in its complete form: + *

+ * -XX:+UseSerialGC -Xms1024m -Xmx1024m -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:/path/to/file/gc.log
+ * 
+ * Where: + *
    + *
  • -XX:+UseSerialGC - specify the serial garbage collector.
  • + *
  • -Xms1024m - specify the minimal heap size.
  • + *
  • -Xmx1024m - specify the maximal heap size.
  • + *
  • -verbose:gc - activate the logging of garbage collection information in its simplest form.
  • + *
  • -XX:+PrintGCDetails - activate detailed information about garbage collection.
  • + *
  • -XX:+PrintGCTimeStamps - include a timestamp in the output reflecting the real-time passed in seconds since the JVM started.
  • + *
  • -XX:+PrintGCDateStamps - include the absolute date and time at the start of each line.
  • + *
  • -Xloggc - by default the GC log is written to stdout. Specify an output file via this argument.
  • + *
+ *

+ * It should be noted that the first three arguments are not strictly necessary but for the purposes or the example + * help really simplify things. + * + */ +public class VerboseGarbageCollectorRunner { + + private static Map stringContainer = new HashMap<>(); + + public static void main(String[] args) { + System.out.println("Start of program!"); + String stringWithPrefix = "stringWithPrefix"; + + // Load Java Heap with 3 M java.lang.String instances + for (int i = 0; i < 3000000; i++) { + String newString = stringWithPrefix + i; + stringContainer.put(newString, newString); + } + System.out.println("MAP size: " + stringContainer.size()); + + // Explicit GC! + System.gc(); + + // Remove 2 M out of 3 M + for (int i = 0; i < 2000000; i++) { + String newString = stringWithPrefix + i; + stringContainer.remove(newString); + } + + System.out.println("MAP size: " + stringContainer.size()); + System.out.println("End of program!"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/heapdump/HeapDump.java b/core-java-perf/src/main/java/com/baeldung/heapdump/HeapDump.java similarity index 100% rename from core-java/src/main/java/com/baeldung/heapdump/HeapDump.java rename to core-java-perf/src/main/java/com/baeldung/heapdump/HeapDump.java diff --git a/core-java/src/main/java/com/baeldung/jmx/Game.java b/core-java-perf/src/main/java/com/baeldung/jmx/Game.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jmx/Game.java rename to core-java-perf/src/main/java/com/baeldung/jmx/Game.java diff --git a/core-java/src/main/java/com/baeldung/jmx/GameMBean.java b/core-java-perf/src/main/java/com/baeldung/jmx/GameMBean.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jmx/GameMBean.java rename to core-java-perf/src/main/java/com/baeldung/jmx/GameMBean.java diff --git a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java rename to core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java b/core-java-perf/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java similarity index 100% rename from core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java rename to core-java-perf/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java diff --git a/core-java/src/main/java/com/baeldung/outofmemoryerror/OutOfMemoryGCLimitExceed.java b/core-java-perf/src/main/java/com/baeldung/outofmemoryerror/OutOfMemoryGCLimitExceed.java similarity index 100% rename from core-java/src/main/java/com/baeldung/outofmemoryerror/OutOfMemoryGCLimitExceed.java rename to core-java-perf/src/main/java/com/baeldung/outofmemoryerror/OutOfMemoryGCLimitExceed.java diff --git a/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml b/core-java-perf/src/main/resources/logback.xml similarity index 57% rename from sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml rename to core-java-perf/src/main/resources/logback.xml index 7d900d8ea8..56af2d397e 100644 --- a/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml +++ b/core-java-perf/src/main/resources/logback.xml @@ -7,6 +7,12 @@ + + + + + + diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java b/core-java-perf/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java rename to core-java-perf/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java b/core-java-perf/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java rename to core-java-perf/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java b/core-java-perf/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java rename to core-java-perf/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java b/core-java-perf/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java rename to core-java-perf/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java b/core-java-perf/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java rename to core-java-perf/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java b/core-java-perf/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java rename to core-java-perf/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java diff --git a/core-java-security/README.md b/core-java-security/README.md new file mode 100644 index 0000000000..415171094b --- /dev/null +++ b/core-java-security/README.md @@ -0,0 +1,11 @@ +## 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 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) \ No newline at end of file diff --git a/core-java-security/pom.xml b/core-java-security/pom.xml new file mode 100644 index 0000000000..cf91121465 --- /dev/null +++ b/core-java-security/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.baeldung + core-java-security + 0.1.0-SNAPSHOT + jar + core-java-security + + + 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 + + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + + + + + + + 3.8.1 + 1.55 + 1.10 + + + 3.10.0 + + + + diff --git a/core-java/src/main/java/com/baeldung/cipher/Encryptor.java b/core-java-security/src/main/java/com/baeldung/cipher/Encryptor.java similarity index 100% rename from core-java/src/main/java/com/baeldung/cipher/Encryptor.java rename to core-java-security/src/main/java/com/baeldung/cipher/Encryptor.java diff --git a/core-java/src/main/java/com/baeldung/encrypt/FileEncrypterDecrypter.java b/core-java-security/src/main/java/com/baeldung/encrypt/FileEncrypterDecrypter.java similarity index 100% rename from core-java/src/main/java/com/baeldung/encrypt/FileEncrypterDecrypter.java rename to core-java-security/src/main/java/com/baeldung/encrypt/FileEncrypterDecrypter.java diff --git a/core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java similarity index 100% rename from core-java/src/main/java/com/baeldung/hashing/SHA256Hashing.java rename to core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java diff --git a/core-java/src/main/java/com/baeldung/keystore/JavaKeyStore.java b/core-java-security/src/main/java/com/baeldung/keystore/JavaKeyStore.java similarity index 100% rename from core-java/src/main/java/com/baeldung/keystore/JavaKeyStore.java rename to core-java-security/src/main/java/com/baeldung/keystore/JavaKeyStore.java diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java rename to core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java rename to core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java diff --git a/core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java similarity index 100% rename from core-java/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java rename to core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java diff --git a/core-java/src/main/java/com/baeldung/ssl/SecureConnection.java b/core-java-security/src/main/java/com/baeldung/ssl/SecureConnection.java similarity index 100% rename from core-java/src/main/java/com/baeldung/ssl/SecureConnection.java rename to core-java-security/src/main/java/com/baeldung/ssl/SecureConnection.java diff --git a/core-java/src/main/java/com/baeldung/ssl/example/SimpleClient.java b/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleClient.java similarity index 100% rename from core-java/src/main/java/com/baeldung/ssl/example/SimpleClient.java rename to core-java-security/src/main/java/com/baeldung/ssl/example/SimpleClient.java diff --git a/core-java/src/main/java/com/baeldung/ssl/example/SimpleServer.java b/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleServer.java similarity index 100% rename from core-java/src/main/java/com/baeldung/ssl/example/SimpleServer.java rename to core-java-security/src/main/java/com/baeldung/ssl/example/SimpleServer.java diff --git a/core-java-security/src/main/resources/logback.xml b/core-java-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-security/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/cipher/EncryptorUnitTest.java b/core-java-security/src/test/java/com/baeldung/cipher/EncryptorUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/cipher/EncryptorUnitTest.java rename to core-java-security/src/test/java/com/baeldung/cipher/EncryptorUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/encrypt/FileEncrypterDecrypterIntegrationTest.java b/core-java-security/src/test/java/com/baeldung/encrypt/FileEncrypterDecrypterIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/encrypt/FileEncrypterDecrypterIntegrationTest.java rename to core-java-security/src/test/java/com/baeldung/encrypt/FileEncrypterDecrypterIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java b/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java rename to core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java b/core-java-security/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java similarity index 87% rename from core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java rename to core-java-security/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java index cb2a9f1c49..7473c52a35 100644 --- a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java +++ b/core-java-security/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java @@ -4,15 +4,24 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; + import sun.security.x509.AlgorithmId; import sun.security.x509.CertificateAlgorithmId; import sun.security.x509.CertificateSerialNumber; import sun.security.x509.CertificateValidity; import sun.security.x509.CertificateVersion; import sun.security.x509.CertificateX509Key; +import sun.security.x509.SubjectAlternativeNameExtension; import sun.security.x509.X500Name; import sun.security.x509.X509CertImpl; import sun.security.x509.X509CertInfo; +import sun.security.x509.CertificateExtensions; +import sun.security.x509.GeneralNames; +import sun.security.x509.GeneralName; +import sun.security.x509.GeneralNameInterface; +import sun.security.x509.DNSName; +import sun.security.x509.IPAddressName; +import sun.security.util.DerOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; @@ -188,6 +197,23 @@ public class JavaKeyStoreUnitTest { Date validTo = new Date(validFrom.getTime() + 50L * 365L * 24L * 60L * 60L * 1000L); //50 years CertificateValidity validity = new CertificateValidity(validFrom, validTo); certInfo.set(X509CertInfo.VALIDITY, validity); + + GeneralNameInterface dnsName = new DNSName("baeldung.com"); + DerOutputStream dnsNameOutputStream = new DerOutputStream(); + dnsName.encode(dnsNameOutputStream); + + GeneralNameInterface ipAddress = new IPAddressName("127.0.0.1"); + DerOutputStream ipAddressOutputStream = new DerOutputStream(); + ipAddress.encode(ipAddressOutputStream); + + GeneralNames generalNames = new GeneralNames(); + generalNames.add(new GeneralName(dnsName)); + generalNames.add(new GeneralName(ipAddress)); + + CertificateExtensions ext = new CertificateExtensions(); + ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(generalNames)); + + certInfo.set(X509CertInfo.EXTENSIONS, ext); // Create certificate and sign it X509CertImpl cert = new X509CertImpl(certInfo); @@ -202,4 +228,5 @@ public class JavaKeyStoreUnitTest { return newCert; } + } \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java rename to core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java rename to core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java b/core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java similarity index 100% rename from core-java/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java rename to core-java-security/src/test/java/org/baeldung/java/md5/JavaMD5UnitTest.java diff --git a/core-java/src/test/resources/test_md5.txt b/core-java-security/src/test/resources/test_md5.txt similarity index 100% rename from core-java/src/test/resources/test_md5.txt rename to core-java-security/src/test/resources/test_md5.txt diff --git a/core-java-sun/README.md b/core-java-sun/README.md index 9cf8b26f1b..e2dba76b41 100644 --- a/core-java-sun/README.md +++ b/core-java-sun/README.md @@ -4,3 +4,4 @@ ### Relevant Articles: - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) +- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe) \ No newline at end of file diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml index 57d5e9da5b..ef68c947ce 100644 --- a/core-java-sun/pom.xml +++ b/core-java-sun/pom.xml @@ -262,7 +262,7 @@ - 2.8.5 + 2.9.7 23.0 diff --git a/core-java-sun/src/main/java/com/baeldung/README.md b/core-java-sun/src/main/java/com/baeldung/README.md index 51809b2882..7d843af9ea 100644 --- a/core-java-sun/src/main/java/com/baeldung/README.md +++ b/core-java-sun/src/main/java/com/baeldung/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java) diff --git a/core-java/src/test/java/com/baeldung/unsafe/CASCounter.java b/core-java-sun/src/test/java/com/baeldung/unsafe/CASCounter.java similarity index 100% rename from core-java/src/test/java/com/baeldung/unsafe/CASCounter.java rename to core-java-sun/src/test/java/com/baeldung/unsafe/CASCounter.java diff --git a/core-java/src/test/java/com/baeldung/unsafe/OffHeapArray.java b/core-java-sun/src/test/java/com/baeldung/unsafe/OffHeapArray.java similarity index 100% rename from core-java/src/test/java/com/baeldung/unsafe/OffHeapArray.java rename to core-java-sun/src/test/java/com/baeldung/unsafe/OffHeapArray.java diff --git a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java b/core-java-sun/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java rename to core-java-sun/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java diff --git a/core-java/README.md b/core-java/README.md index 7617897e95..03b77186b0 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -5,84 +5,43 @@ ### Relevant Articles: - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) - [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) -- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) -- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets) -- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) - [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) - [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) - [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java) -- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) -- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm) -- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) -- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda) - [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) -- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe) -- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) - [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend) -- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability) - [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) -- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string) - [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) - [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri) -- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast) -- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) -- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) - [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) -- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) -- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) -- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) -- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) -- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) -- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) -- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat) +- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) - [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os) - [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) - [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) -- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [Class Loaders in Java](http://www.baeldung.com/java-classloaders) -- [Sending Emails with Java](http://www.baeldung.com/java-email) -- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl) -- [Java KeyStore API](http://www.baeldung.com/java-keystore) - [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Guide to Java Clock Class](http://www.baeldung.com/java-clock) -- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) -- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) -- [Singletons in Java](http://www.baeldung.com/java-singleton) -- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) -- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) -- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) -- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) -- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) -- [Console I/O in Java](http://www.baeldung.com/java-console-input-output) - [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) -- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) - [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) - [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation) -- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) -- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) -- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) -- [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) -- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture) -- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) -- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) -- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks) -- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format) -- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures) -- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree) +- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) +- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) +- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) +- [Graphs in Java](https://www.baeldung.com/java-graphs) +- [Console I/O in Java](http://www.baeldung.com/java-console-input-output) diff --git a/core-java/pom.xml b/core-java/pom.xml index 9fbc8f6810..6c58653d5a 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -3,8 +3,8 @@ 4.0.0 core-java 0.1.0-SNAPSHOT - jar core-java + jar com.baeldung @@ -24,11 +24,6 @@ commons-lang3 ${commons-lang3.version} - - org.bouncycastle - bcprov-jdk15on - ${bouncycastle.version} - org.unix4j unix4j-command @@ -75,12 +70,6 @@ ${assertj-core.version} test - - - commons-codec - commons-codec - ${commons-codec.version} - org.javamoney moneta @@ -121,32 +110,11 @@ jmh-generator-annprocess ${jmh-generator-annprocess.version} - - org.springframework - spring-web - ${springframework.spring-web.version} - com.h2database h2 ${h2database.version} - - javax.mail - mail - ${javax.mail.version} - - - - org.apache.tika - tika-core - ${tika.version} - - - net.sf.jmimemagic - jmimemagic - ${jmime-magic.version} - org.javassist @@ -482,13 +450,11 @@ - 2.8.5 + 2.9.7 2.8.2 3.5 - 1.55 - 1.10 2.5 3.6.1 1.0.3 @@ -505,7 +471,6 @@ 2.21.0 - 4.3.4.RELEASE 1.1 1.4.197 @@ -514,16 +479,12 @@ 1.19 3.0.0-M1 - 1.5.0-b01 3.0.2 1.4.4 3.1.1 2.0.3.RELEASE 1.6.0 61.1 - - 1.18 - 0.1.5 3.21.0-GA diff --git a/core-java/src/main/java/com/baeldung/README.md b/core-java/src/main/java/com/baeldung/README.md index 51809b2882..7d843af9ea 100644 --- a/core-java/src/main/java/com/baeldung/README.md +++ b/core-java/src/main/java/com/baeldung/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java) diff --git a/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java new file mode 100644 index 0000000000..20a13178cc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java @@ -0,0 +1,11 @@ +package com.baeldung.basicsyntax; + +public class SimpleAddition { + + public static void main(String[] args) { + int a = 10; + int b = 5; + double c = a + b; + System.out.println( a + " + " + b + " = " + c); + } +} diff --git a/core-java/src/main/java/com/baeldung/graph/Graph.java b/core-java/src/main/java/com/baeldung/graph/Graph.java new file mode 100644 index 0000000000..43b5c0aa08 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/Graph.java @@ -0,0 +1,76 @@ +package com.baeldung.graph; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Graph { + private Map> adjVertices; + + Graph() { + this.adjVertices = new HashMap>(); + } + + void addVertex(String label) { + adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>()); + } + + void removeVertex(String label) { + Vertex v = new Vertex(label); + adjVertices.values().stream().map(e -> e.remove(v)).collect(Collectors.toList()); + adjVertices.remove(new Vertex(label)); + } + + void addEdge(String label1, String label2) { + Vertex v1 = new Vertex(label1); + Vertex v2 = new Vertex(label2); + adjVertices.get(v1).add(v2); + adjVertices.get(v2).add(v1); + } + + void removeEdge(String label1, String label2) { + Vertex v1 = new Vertex(label1); + Vertex v2 = new Vertex(label2); + List eV1 = adjVertices.get(v1); + List eV2 = adjVertices.get(v2); + if (eV1 != null) + eV1.remove(v2); + if (eV2 != null) + eV2.remove(v1); + } + + List getAdjVertices(String label) { + return adjVertices.get(new Vertex(label)); + } + + String printGraph() { + StringBuffer sb = new StringBuffer(); + for(Vertex v : adjVertices.keySet()) { + sb.append(v); + sb.append(adjVertices.get(v)); + } + return sb.toString(); + } + + class Vertex { + String label; + Vertex(String label) { + this.label = label; + } + @Override + public boolean equals(Object obj) { + Vertex vertex = (Vertex) obj; + return vertex.label == label; + } + @Override + public int hashCode() { + return label.hashCode(); + } + @Override + public String toString() { + return label; + } + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java b/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java new file mode 100644 index 0000000000..479e653a5c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java @@ -0,0 +1,44 @@ +package com.baeldung.graph; + +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; + +import com.baeldung.graph.Graph.Vertex; + +public class GraphTraversal { + static Set depthFirstTraversal(Graph graph, String root) { + Set visited = new LinkedHashSet(); + Stack stack = new Stack(); + stack.push(root); + while (!stack.isEmpty()) { + String vertex = stack.pop(); + if (!visited.contains(vertex)) { + visited.add(vertex); + for (Vertex v : graph.getAdjVertices(vertex)) { + stack.push(v.label); + } + } + } + return visited; + } + + static Set breadthFirstTraversal(Graph graph, String root) { + Set visited = new LinkedHashSet(); + Queue queue = new LinkedList(); + queue.add(root); + visited.add(root); + while (!queue.isEmpty()) { + String vertex = queue.poll(); + for (Vertex v : graph.getAdjVertices(vertex)) { + if (!visited.contains(v.label)) { + visited.add(v.label); + queue.add(v.label); + } + } + } + return visited; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/networking/README.md b/core-java/src/main/java/com/baeldung/networking/README.md deleted file mode 100644 index b9e827f085..0000000000 --- a/core-java/src/main/java/com/baeldung/networking/README.md +++ /dev/null @@ -1,5 +0,0 @@ -### Relevant Articles: -- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java) -- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java) -- [A Guide to the Java URL](http://www.baeldung.com/java-url) -- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) diff --git a/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java b/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java new file mode 100644 index 0000000000..3d451f6f50 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java @@ -0,0 +1,61 @@ +package com.baeldung.printf; + +import java.util.Date; +import java.util.Locale; + +public class PrintfExamples { + + public static void main(String[] args) { + + printfNewLine(); + printfChar(); + printfString(); + printfNumber(); + printfDateTime(); + printfBoolean(); + } + + private static void printfNewLine() { + System.out.printf("baeldung%nline%nterminator"); + } + + private static void printfString() { + System.out.printf("'%s' %n", "baeldung"); + System.out.printf("'%S' %n", "baeldung"); + System.out.printf("'%15s' %n", "baeldung"); + System.out.printf("'%-10s' %n", "baeldung"); + } + + private static void printfChar() { + System.out.printf("%c%n", 's'); + System.out.printf("%C%n", 's'); + } + + private static void printfNumber() { + System.out.printf("simple integer: %d%n", 10000L); + + System.out.printf(Locale.US, "%,d %n", 10000); + System.out.printf(Locale.ITALY, "%,d %n", 10000); + + System.out.printf("%f%n", 5.1473); + System.out.printf("'%5.2f'%n", 5.1473); + System.out.printf("'%5.2e'%n", 5.1473); + } + + private static void printfBoolean() { + System.out.printf("%b%n", null); + System.out.printf("%B%n", false); + System.out.printf("%B%n", 5.3); + System.out.printf("%b%n", "random text"); + } + + private static void printfDateTime() { + Date date = new Date(); + System.out.printf("%tT%n", date); + System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date); + System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date); + + System.out.printf("%1$tA %1$tB %1$tY %n", date); + System.out.printf("%1$td.%1$tm.%1$ty %n", date); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java b/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java new file mode 100644 index 0000000000..d955d56d95 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.graph; + +import org.junit.Assert; +import org.junit.Test; + +public class GraphTraversalUnitTest { + @Test + public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() { + Graph graph = createGraph(); + Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]", + GraphTraversal.depthFirstTraversal(graph, "Bob").toString()); + } + + @Test + public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() { + Graph graph = createGraph(); + Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]", + GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); + } + + Graph createGraph() { + Graph graph = new Graph(); + graph.addVertex("Bob"); + graph.addVertex("Alice"); + graph.addVertex("Mark"); + graph.addVertex("Rob"); + graph.addVertex("Maria"); + graph.addEdge("Bob", "Alice"); + graph.addEdge("Bob", "Rob"); + graph.addEdge("Alice", "Mark"); + graph.addEdge("Rob", "Mark"); + graph.addEdge("Alice", "Maria"); + graph.addEdge("Rob", "Maria"); + return graph; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java new file mode 100644 index 0000000000..b669947d9c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java @@ -0,0 +1,171 @@ +package com.baeldung.java.properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; + +import org.junit.Test; + +public class PropertiesUnitTest { + + @Test + public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + String catalogConfigPath = rootPath + "catalog"; + + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + Properties catalogProps = new Properties(); + catalogProps.load(new FileInputStream(catalogConfigPath)); + + String appVersion = appProps.getProperty("version"); + assertEquals("1.0", appVersion); + + assertEquals("files", catalogProps.getProperty("c1")); + } + + @Test + public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String iconConfigPath = rootPath + "icons.xml"; + Properties iconProps = new Properties(); + iconProps.loadFromXML(new FileInputStream(iconConfigPath)); + + assertEquals("icon1.jpg", iconProps.getProperty("fileIcon")); + } + + @Test + public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String appVersion = appProps.getProperty("version"); + String appName = appProps.getProperty("name", "defaultName"); + String appGroup = appProps.getProperty("group", "baeldung"); + String appDownloadAddr = appProps.getProperty("downloadAddr"); + + assertEquals("1.0", appVersion); + assertEquals("TestApp", appName); + assertEquals("baeldung", appGroup); + assertNull(appDownloadAddr); + } + + @Test(expected = Exception.class) + public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + float appVerFloat = (float) appProps.get("version"); + } + + @Test + public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + appProps.setProperty("name", "NewAppName"); + appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); + + String newAppName = appProps.getProperty("name"); + assertEquals("NewAppName", newAppName); + + String newAppDownloadAddr = appProps.getProperty("downloadAddr"); + assertEquals("www.baeldung.com/downloads", newAppDownloadAddr); + } + + @Test + public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String versionBeforeRemoval = appProps.getProperty("version"); + assertEquals("1.0", versionBeforeRemoval); + + appProps.remove("version"); + String versionAfterRemoval = appProps.getProperty("version"); + assertNull(versionAfterRemoval); + } + + @Test + public void whenPropertiesStoredInFile_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appConfigPath)); + + String newAppConfigPropertiesFile = rootPath + "newApp.properties"; + appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file"); + + String newAppConfigXmlFile = rootPath + "newApp.xml"; + appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file"); + } + + @Test + public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + + String defaultConfigPath = rootPath + "default.properties"; + Properties defaultProps = new Properties(); + defaultProps.load(new FileInputStream(defaultConfigPath)); + + String appConfigPath = rootPath + "app.properties"; + Properties appProps = new Properties(defaultProps); + appProps.load(new FileInputStream(appConfigPath)); + + String appName = appProps.getProperty("name"); + String appVersion = appProps.getProperty("version"); + String defaultSite = appProps.getProperty("site"); + + assertEquals("1.0", appVersion); + assertEquals("TestApp", appName); + assertEquals("www.google.com", defaultSite); + } + + @Test + public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException { + + String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + String appPropsPath = rootPath + "app.properties"; + Properties appProps = new Properties(); + appProps.load(new FileInputStream(appPropsPath)); + + appProps.list(System.out); // list all key-value pairs + + Enumeration valueEnumeration = appProps.elements(); + while (valueEnumeration.hasMoreElements()) { + System.out.println(valueEnumeration.nextElement()); + } + + Enumeration keyEnumeration = appProps.keys(); + while (keyEnumeration.hasMoreElements()) { + System.out.println(keyEnumeration.nextElement()); + } + + int size = appProps.size(); + assertEquals(3, size); + } +} diff --git a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherManualTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java rename to core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherManualTest.java index 2be6b6ad4b..f44968a5a7 100644 --- a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java +++ b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherManualTest.java @@ -11,7 +11,7 @@ import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; -public class OptimizedMatcherUnitTest { +public class OptimizedMatcherManualTest { private String action; diff --git a/core-java/src/test/resources/app.properties b/core-java/src/test/resources/app.properties new file mode 100644 index 0000000000..ff6174ec2a --- /dev/null +++ b/core-java/src/test/resources/app.properties @@ -0,0 +1,3 @@ +version=1.0 +name=TestApp +date=2016-11-12 \ No newline at end of file diff --git a/core-java/src/test/resources/catalog b/core-java/src/test/resources/catalog new file mode 100644 index 0000000000..488513d0ce --- /dev/null +++ b/core-java/src/test/resources/catalog @@ -0,0 +1,3 @@ +c1=files +c2=images +c3=videos \ No newline at end of file diff --git a/core-java/src/test/resources/default.properties b/core-java/src/test/resources/default.properties new file mode 100644 index 0000000000..df1bab371c --- /dev/null +++ b/core-java/src/test/resources/default.properties @@ -0,0 +1,4 @@ +site=www.google.com +name=DefaultAppName +topic=Properties +category=core-java \ No newline at end of file diff --git a/core-java/src/test/resources/icons.xml b/core-java/src/test/resources/icons.xml new file mode 100644 index 0000000000..0db7b2699a --- /dev/null +++ b/core-java/src/test/resources/icons.xml @@ -0,0 +1,8 @@ + + + + xml example + icon1.jpg + icon2.jpg + icon3.jpg + \ No newline at end of file diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 1b04b71228..05f07e7e7e 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -34,7 +34,6 @@ - [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) -- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) - [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) @@ -47,3 +46,4 @@ - [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) +- [Generate a Random Alphanumeric String in Kotlin](https://www.baeldung.com/kotlin-random-alphanumeric-string) diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 2b559b19e0..8b871f28ee 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -3,6 +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 core-kotlin + core-kotlin jar @@ -71,6 +72,17 @@ injekt-core 1.16.1 + + uy.kohesive.kovert + kovert-vertx + [1.5.0,1.6.0) + + + nl.komponents.kovenant + kovenant + + + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt b/core-kotlin/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt new file mode 100644 index 0000000000..ca0b13cdc7 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt @@ -0,0 +1,23 @@ +package com.baeldung.contract + +import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract + +@ExperimentalContracts +inline fun myRun(block: () -> R): R { + contract { + callsInPlace(block, InvocationKind.EXACTLY_ONCE) + } + return block() +} + +@ExperimentalContracts +fun callsInPlace() { + val i: Int + myRun { + i = 1 // Without contract initialization is forbidden due to possible re-assignment + } + println(i) // Without contract variable might be uninitialized +} + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt b/core-kotlin/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt new file mode 100644 index 0000000000..56f667af82 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt @@ -0,0 +1,43 @@ +package com.baeldung.contract + +import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.contract + +data class Request(val arg: String) + +class Service { + + @ExperimentalContracts + fun process(request: Request?) { + validate(request) + println(request.arg) + } + +} + +@ExperimentalContracts +private fun validate(request: Request?) { + contract { + returns() implies (request != null) + } + if (request == null) { + throw IllegalArgumentException("Undefined request") + } +} + +data class MyEvent(val message: String) + +@ExperimentalContracts +fun processEvent(event: Any?) { + if (isInterested(event)) { + println(event.message) // Compiler makes smart cast here with the help of contract + } +} + +@ExperimentalContracts +fun isInterested(event: Any?): Boolean { + contract { + returns(true) implies (event is MyEvent) + } + return event is MyEvent +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt b/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt new file mode 100644 index 0000000000..239c425c03 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/functions/Inline.kt @@ -0,0 +1,28 @@ +package com.baeldung.functions + +import kotlin.random.Random + +/** + * An extension function on all collections to apply a function to all collection + * elements. + */ +fun Collection.each(block: (T) -> Unit) { + for (e in this) block(e) +} + +/** + * In order to see the the JVM bytecode: + * 1. Compile the Kotlin file using `kotlinc Inline.kt` + * 2. Take a peek at the bytecode using the `javap -c InlineKt` + */ +fun main() { + val numbers = listOf(1, 2, 3, 4, 5) + val random = random() + + numbers.each { println(random * it) } // capturing the random variable +} + +/** + * Generates a random number. + */ +private fun random(): Int = Random.nextInt() \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt new file mode 100644 index 0000000000..5b46b9570f --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt @@ -0,0 +1,14 @@ +package com.baeldung.inline.classes + +interface Drawable { + fun draw() +} + +inline class CircleRadius(private val circleRadius : Double) : Drawable { + val diameterOfCircle get() = 2 * circleRadius + fun areaOfCircle() = 3.14 * circleRadius * circleRadius + + override fun draw() { + println("Draw my circle") + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt new file mode 100644 index 0000000000..430fa509da --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt @@ -0,0 +1,3 @@ +package com.baeldung.inline.classes + +inline class InlineDoubleWrapper(val doubleValue : Double) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt new file mode 100644 index 0000000000..da2bbe4208 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt @@ -0,0 +1,73 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.core.HttpVerb +import uy.kohesive.kovert.core.Location +import uy.kohesive.kovert.core.Verb +import uy.kohesive.kovert.core.VerbAlias +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class AnnotatedServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(AnnotatedServer::class.java) + + @JvmStatic + fun main(args: Array) { + AnnotatedServer().start() + } + } + + @VerbAlias("show", HttpVerb.GET) + class AnnotatedController { + fun RoutingContext.showStringById(id: String) = id + + @Verb(HttpVerb.GET) + @Location("/ping/:id") + fun RoutingContext.ping(id: String) = id + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", AnnotatedServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(AnnotatedController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt new file mode 100644 index 0000000000..a596391ed8 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt @@ -0,0 +1,75 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.core.HttpErrorCode +import uy.kohesive.kovert.core.HttpErrorCodeWithBody +import uy.kohesive.kovert.core.HttpErrorForbidden +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class ErrorServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(ErrorServer::class.java) + + @JvmStatic + fun main(args: Array) { + ErrorServer().start() + } + } + + class ErrorController { + fun RoutingContext.getForbidden() { + throw HttpErrorForbidden() + } + fun RoutingContext.getError() { + throw HttpErrorCode("Something went wrong", 590) + } + fun RoutingContext.getErrorbody() { + throw HttpErrorCodeWithBody("Something went wrong", 591, "Body here") + } + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", ErrorServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(ErrorController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt new file mode 100644 index 0000000000..310fe2a7a0 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt @@ -0,0 +1,76 @@ +package com.baeldung.kovert + +import com.fasterxml.jackson.annotation.JsonProperty +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + +class JsonServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(JsonServer::class.java) + + @JvmStatic + fun main(args: Array) { + JsonServer().start() + } + } + + data class Person( + @JsonProperty("_id") + val id: String, + val name: String, + val job: String + ) + + class JsonController { + fun RoutingContext.getPersonById(id: String) = Person( + id = id, + name = "Tony Stark", + job = "Iron Man" + ) + fun RoutingContext.putPersonById(id: String, person: Person) = person + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", JsonServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(JsonController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt new file mode 100644 index 0000000000..98ce775e66 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt @@ -0,0 +1,57 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + +class NoopServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(NoopServer::class.java) + + @JvmStatic + fun main(args: Array) { + NoopServer().start() + } + } + + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", NoopServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt new file mode 100644 index 0000000000..86ca482808 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt @@ -0,0 +1,68 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class SecuredServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(SecuredServer::class.java) + + @JvmStatic + fun main(args: Array) { + SecuredServer().start() + } + } + + class SecuredContext(private val routingContext: RoutingContext) { + val authenticated = routingContext.request().getHeader("Authorization") == "Secure" + } + + class SecuredController { + fun SecuredContext.getSecured() = this.authenticated + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SecuredServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(SecuredController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt new file mode 100644 index 0000000000..172469ab46 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt @@ -0,0 +1,65 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class SimpleServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(SimpleServer::class.java) + + @JvmStatic + fun main(args: Array) { + SimpleServer().start() + } + } + + class SimpleController { + fun RoutingContext.getStringById(id: String) = id + fun RoutingContext.get_truncatedString_by_id(id: String, length: Int = 1) = id.subSequence(0, length) + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SimpleServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(SimpleController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Money.kt b/core-kotlin/src/main/kotlin/com/baeldung/operators/Money.kt new file mode 100644 index 0000000000..93eb78c5b6 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/operators/Money.kt @@ -0,0 +1,31 @@ +package com.baeldung.operators + +import java.math.BigDecimal + +enum class Currency { + DOLLARS, EURO +} + +class Money(val amount: BigDecimal, val currency: Currency) : Comparable { + + override fun compareTo(other: Money): Int = + convert(Currency.DOLLARS).compareTo(other.convert(Currency.DOLLARS)) + + fun convert(currency: Currency): BigDecimal = TODO() + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is Money) return false + + if (amount != other.amount) return false + if (currency != other.currency) return false + + return true + } + + override fun hashCode(): Int { + var result = amount.hashCode() + result = 31 * result + currency.hashCode() + return result + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Page.kt b/core-kotlin/src/main/kotlin/com/baeldung/operators/Page.kt new file mode 100644 index 0000000000..1077eb94f9 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/operators/Page.kt @@ -0,0 +1,16 @@ +package com.baeldung.operators + +interface Page { + fun pageNumber(): Int + fun pageSize(): Int + fun elements(): MutableList +} + +operator fun Page.get(index: Int): T = elements()[index] +operator fun Page.get(start: Int, endExclusive: Int): List = elements().subList(start, endExclusive) +operator fun Page.set(index: Int, value: T) { + elements()[index] = value +} + +operator fun Page.contains(element: T): Boolean = element in elements() +operator fun Page.iterator() = elements().iterator() \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Point.kt b/core-kotlin/src/main/kotlin/com/baeldung/operators/Point.kt new file mode 100644 index 0000000000..e3282e64cc --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/operators/Point.kt @@ -0,0 +1,31 @@ +package com.baeldung.operators + +data class Point(val x: Int, val y: Int) + +operator fun Point.unaryMinus() = Point(-x, -y) +operator fun Point.not() = Point(y, x) +operator fun Point.inc() = Point(x + 1, y + 1) +operator fun Point.dec() = Point(x - 1, y - 1) + +operator fun Point.plus(other: Point): Point = Point(x + other.x, y + other.y) +operator fun Point.minus(other: Point): Point = Point(x - other.x, y - other.y) +operator fun Point.times(other: Point): Point = Point(x * other.x, y * other.y) +operator fun Point.div(other: Point): Point = Point(x / other.x, y / other.y) +operator fun Point.rem(other: Point): Point = Point(x % other.x, y % other.y) +operator fun Point.times(factor: Int): Point = Point(x * factor, y * factor) +operator fun Int.times(point: Point): Point = Point(point.x * this, point.y * this) + +class Shape { + val points = mutableListOf() + + operator fun Point.unaryPlus() { + points.add(this) + } +} + +fun shape(init: Shape.() -> Unit): Shape { + val shape = Shape() + shape.init() + + return shape +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/operators/Utils.kt b/core-kotlin/src/main/kotlin/com/baeldung/operators/Utils.kt new file mode 100644 index 0000000000..0f16544f38 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/operators/Utils.kt @@ -0,0 +1,8 @@ +package com.baeldung.operators + +import java.math.BigInteger + +operator fun MutableCollection.plusAssign(element: T) { + add(element) +} +operator fun BigInteger.plus(other: Int): BigInteger = add(BigInteger("$other")) \ No newline at end of file diff --git a/core-kotlin/src/main/resources/kovert.conf b/core-kotlin/src/main/resources/kovert.conf new file mode 100644 index 0000000000..3b08641693 --- /dev/null +++ b/core-kotlin/src/main/resources/kovert.conf @@ -0,0 +1,15 @@ +{ + kovert: { + vertx: { + clustered: false + } + server: { + listeners: [ + { + host: "0.0.0.0" + port: "8000" + } + ] + } + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt new file mode 100644 index 0000000000..8de378b6dd --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt @@ -0,0 +1,19 @@ +package com.baeldung.inline.classes + +import org.junit.Test +import kotlin.test.assertEquals + +class CircleRadiusTest { + + @Test + fun givenRadius_ThenDiameterIsCorrectlyCalculated() { + val radius = CircleRadius(5.0) + assertEquals(10.0, radius.diameterOfCircle) + } + + @Test + fun givenRadius_ThenAreaIsCorrectlyCalculated() { + val radius = CircleRadius(5.0) + assertEquals(78.5, radius.areaOfCircle()) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt new file mode 100644 index 0000000000..349c90d6f4 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt @@ -0,0 +1,13 @@ +package com.baeldung.inline.classes + +import org.junit.Test +import kotlin.test.assertEquals + +class InlineDoubleWrapperTest { + + @Test + fun whenInclineClassIsUsed_ThenPropertyIsReadCorrectly() { + val piDoubleValue = InlineDoubleWrapper(3.14) + assertEquals(3.14, piDoubleValue.doubleValue) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/ConstantUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/ConstantUnitTest.kt new file mode 100644 index 0000000000..51d45b8df0 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/ConstantUnitTest.kt @@ -0,0 +1,17 @@ +import com.baeldung.kotlin.constant.TestKotlinConstantClass +import com.baeldung.kotlin.constant.TestKotlinConstantObject +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class ConstantUnitTest { + + @Test + fun givenConstant_whenCompareWithActualValue_thenReturnTrue() { + assertEquals(10, TestKotlinConstantObject.COMPILE_TIME_CONST) + assertEquals(30, TestKotlinConstantObject.RUN_TIME_CONST) + assertEquals(20, TestKotlinConstantObject.JAVA_STATIC_FINAL_FIELD) + + assertEquals(40, TestKotlinConstantClass.COMPANION_OBJECT_NUMBER) + } +} + 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 new file mode 100644 index 0000000000..8bcc327999 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantClass.kt @@ -0,0 +1,8 @@ +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/constant/TestKotlinConstantObject.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantObject.kt new file mode 100644 index 0000000000..815fdeaf14 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/constant/TestKotlinConstantObject.kt @@ -0,0 +1,15 @@ +package com.baeldung.kotlin.constant + + +object TestKotlinConstantObject { + const val COMPILE_TIME_CONST = 10 + + val RUN_TIME_CONST: Int + + @JvmField + val JAVA_STATIC_FINAL_FIELD = 20 + + init { + RUN_TIME_CONST = TestKotlinConstantObject.COMPILE_TIME_CONST + 20; + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/operators/PageTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/operators/PageTest.kt new file mode 100644 index 0000000000..4217fc0c08 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/operators/PageTest.kt @@ -0,0 +1,28 @@ +package com.baeldung.operators + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class PageTest { + + private val page = PageImpl(1, 10, "Java", "Kotlin", "Scala") + + @Test + fun `Get convention should work as expected`() { + assertEquals(page[1], "Kotlin") + assertEquals(page[1, 3], listOf("Kotlin", "Scala")) + } + + @Test + fun `In convention should work on a page as expected`() { + assertTrue("Kotlin" in page) + } + +} + +private class PageImpl(val page: Int, val size: Int, vararg val elements: T) : Page { + override fun pageNumber(): Int = page + override fun pageSize(): Int = size + override fun elements(): MutableList = mutableListOf(*elements) +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/operators/PointTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/operators/PointTest.kt new file mode 100644 index 0000000000..168ab6431d --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/operators/PointTest.kt @@ -0,0 +1,48 @@ +package com.baeldung.operators + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class PointTest { + + private val p1 = Point(1, 2) + private val p2 = Point(2, 3) + + @Test + fun `We should be able to add two points together using +`() { + assertEquals(p1 + p2, Point(3, 5)) + } + + @Test + fun `We shoud be able to subtract one point from another using -`() { + assertEquals(p1 - p2, Point(-1, -1)) + } + + @Test + fun `We should be able to multiply two points together with *`() { + assertEquals(p1 * p2, Point(2, 6)) + } + + @Test + fun `We should be able to divide one point by another`() { + assertEquals(p1 / p2, Point(0, 0)) + } + + @Test + fun `We should be able to scale a point by an integral factor`() { + assertEquals(p1 * 2, Point(2, 4)) + assertEquals(2 * p1, Point(2, 4)) + } + + @Test + fun `We should be able to add points to an empty shape`() { + val line = shape { + +Point(0, 0) + +Point(1, 3) + } + + assertTrue(Point(0, 0) in line.points) + assertTrue(Point(1, 3) in line.points) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/operators/UtilsTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/operators/UtilsTest.kt new file mode 100644 index 0000000000..4abe962cb5 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/operators/UtilsTest.kt @@ -0,0 +1,13 @@ +package com.baeldung.operators + +import java.math.BigInteger +import org.junit.Test +import kotlin.test.assertEquals + +class UtilsTest { + + @Test + fun `We should be able to add an int value to an existing BigInteger using +`() { + assertEquals(BigInteger.ZERO + 1, BigInteger.ONE) + } +} \ No newline at end of file diff --git a/core-scala/pom.xml b/core-scala/pom.xml index eb7c1c3330..343f21484a 100644 --- a/core-scala/pom.xml +++ b/core-scala/pom.xml @@ -4,6 +4,7 @@ 4.0.0 core-scala 1.0-SNAPSHOT + core-scala jar diff --git a/couchbase/pom.xml b/couchbase/pom.xml index 4f0f8787ca..7da027597e 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -70,7 +70,7 @@ 2.5.0 4.3.5.RELEASE 3.5 - 2.9.1 + 2.9.7 diff --git a/data-structures/README.md b/data-structures/README.md index b3b1196ce0..2d92068390 100644 --- a/data-structures/README.md +++ b/data-structures/README.md @@ -1,4 +1,4 @@ ## Relevant articles: -- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java) -- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree) +[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) diff --git a/data-structures/pom.xml b/data-structures/pom.xml index c1a1f1d371..4958598234 100644 --- a/data-structures/pom.xml +++ b/data-structures/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung data-structures 0.0.1-SNAPSHOT + data-structures com.baeldung diff --git a/deeplearning4j/README.md b/deeplearning4j/README.md index 7f9c92ec73..14e585cd97 100644 --- a/deeplearning4j/README.md +++ b/deeplearning4j/README.md @@ -2,4 +2,4 @@ This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library. ### Relevant Articles: -- [A Guide to deeplearning4j](http://www.baeldung.com/deeplearning4j) +- [A Guide to Deeplearning4j](http://www.baeldung.com/deeplearning4j) diff --git a/drools/pom.xml b/drools/pom.xml index 009ac8acec..b5cfc7d6dc 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 drools - + drools + com.baeldung parent-spring-4 diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 6f81ec5cff..9fe228bf89 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 dubbo + dubbo parent-modules diff --git a/ethereum/pom.xml b/ethereum/pom.xml index bd1bacb221..85cb260670 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -215,9 +215,9 @@ 5.0.5.RELEASE 1.5.6.RELEASE 2.21.0 - 2.5.0 + 2.9.7 1.3 - 2.9.3 + 2.9.7 2.3.1 3.1.0 2.4.0 diff --git a/ethereum/src/main/java/com/baeldung/web3j/controllers/EthereumRestController.java b/ethereum/src/main/java/com/baeldung/web3j/controllers/EthereumRestController.java index e05517bc79..3238a19ff9 100644 --- a/ethereum/src/main/java/com/baeldung/web3j/controllers/EthereumRestController.java +++ b/ethereum/src/main/java/com/baeldung/web3j/controllers/EthereumRestController.java @@ -32,8 +32,8 @@ public class EthereumRestController { return CompletableFuture.supplyAsync(() -> { try { - CompletableFuture result = web3Service.getBlockNumber(); - responseTransfer.setMessage(result.get().toString()); + EthBlockNumber result = web3Service.getBlockNumber(); + responseTransfer.setMessage(result.toString()); } catch (Exception e) { responseTransfer.setMessage(GENERIC_EXCEPTION); } @@ -51,8 +51,8 @@ public class EthereumRestController { return CompletableFuture.supplyAsync(() -> { try { - CompletableFuture result = web3Service.getEthAccounts(); - responseTransfer.setMessage(result.get().toString()); + EthAccounts result = web3Service.getEthAccounts(); + responseTransfer.setMessage(result.toString()); } catch (Exception e) { responseTransfer.setMessage(GENERIC_EXCEPTION); } @@ -70,8 +70,8 @@ public class EthereumRestController { Instant start = TimeHelper.start(); return CompletableFuture.supplyAsync(() -> { try { - CompletableFuture result = web3Service.getTransactionCount(); - responseTransfer.setMessage(result.get().toString()); + EthGetTransactionCount result = web3Service.getTransactionCount(); + responseTransfer.setMessage(result.toString()); } catch (Exception e) { responseTransfer.setMessage(GENERIC_EXCEPTION); } @@ -88,8 +88,8 @@ public class EthereumRestController { Instant start = TimeHelper.start(); return CompletableFuture.supplyAsync(() -> { try { - CompletableFuture result = web3Service.getEthBalance(); - responseTransfer.setMessage(result.get().toString()); + EthGetBalance result = web3Service.getEthBalance(); + responseTransfer.setMessage(result.toString()); } catch (Exception e) { responseTransfer.setMessage(GENERIC_EXCEPTION); } diff --git a/ethereum/src/main/java/com/baeldung/web3j/services/Web3Service.java b/ethereum/src/main/java/com/baeldung/web3j/services/Web3Service.java index c943ee4006..4b7d01e52b 100644 --- a/ethereum/src/main/java/com/baeldung/web3j/services/Web3Service.java +++ b/ethereum/src/main/java/com/baeldung/web3j/services/Web3Service.java @@ -47,47 +47,47 @@ public class Web3Service { return "0x" + binary; } - public CompletableFuture getBlockNumber() { + public EthBlockNumber getBlockNumber() { EthBlockNumber result = new EthBlockNumber(); try { result = this.web3j.ethBlockNumber().sendAsync().get(); } catch (Exception ex) { System.out.println(GENERIC_EXCEPTION); } - return CompletableFuture.completedFuture(result); + return result; } - public CompletableFuture getEthAccounts() { + public EthAccounts getEthAccounts() { EthAccounts result = new EthAccounts(); try { result = this.web3j.ethAccounts().sendAsync().get(); } catch (Exception ex) { System.out.println(GENERIC_EXCEPTION); } - return CompletableFuture.completedFuture(result); + return result; } - public CompletableFuture getTransactionCount() { + public EthGetTransactionCount getTransactionCount() { EthGetTransactionCount result = new EthGetTransactionCount(); try { result = this.web3j.ethGetTransactionCount(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get(); } catch (Exception ex) { System.out.println(GENERIC_EXCEPTION); } - return CompletableFuture.completedFuture(result); + return result; } - public CompletableFuture getEthBalance() { + public EthGetBalance getEthBalance() { EthGetBalance result = new EthGetBalance(); try { result = this.web3j.ethGetBalance(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get(); } catch (Exception ex) { System.out.println(GENERIC_EXCEPTION); } - return CompletableFuture.completedFuture(result); + return result; } - public CompletableFuture fromScratchContractExample() { + public String fromScratchContractExample() { String contractAddress = ""; @@ -108,13 +108,13 @@ public class Web3Service { } catch (Exception ex) { System.out.println(PLEASE_SUPPLY_REAL_DATA); - return CompletableFuture.completedFuture(PLEASE_SUPPLY_REAL_DATA); + return PLEASE_SUPPLY_REAL_DATA; } - return CompletableFuture.completedFuture(contractAddress); + return contractAddress; } @Async - public CompletableFuture sendTx() { + public String sendTx() { String transactionHash = ""; try { @@ -135,10 +135,10 @@ public class Web3Service { } catch (Exception ex) { System.out.println(PLEASE_SUPPLY_REAL_DATA); - return CompletableFuture.completedFuture(PLEASE_SUPPLY_REAL_DATA); + return PLEASE_SUPPLY_REAL_DATA; } - return CompletableFuture.completedFuture(transactionHash); + return transactionHash; } } diff --git a/ethereum/src/test/java/com/baeldung/web3j/services/EthereumContractUnitTest.java b/ethereum/src/test/java/com/baeldung/web3j/services/EthereumContractUnitTest.java index 382c96e985..ff02659bd5 100644 --- a/ethereum/src/test/java/com/baeldung/web3j/services/EthereumContractUnitTest.java +++ b/ethereum/src/test/java/com/baeldung/web3j/services/EthereumContractUnitTest.java @@ -4,8 +4,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.concurrent.CompletableFuture; - public class EthereumContractUnitTest { private Web3Service web3Service; @@ -17,14 +15,14 @@ public class EthereumContractUnitTest { @Test public void testContract() { - CompletableFuture result = web3Service.fromScratchContractExample(); - assert (result instanceof CompletableFuture); + String result = web3Service.fromScratchContractExample(); + assert (result instanceof String); } @Test public void sendTx() { - CompletableFuture result = web3Service.sendTx(); - assert (result instanceof CompletableFuture); + String result = web3Service.sendTx(); + assert (result instanceof String); } @After diff --git a/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events b/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events deleted file mode 100644 index d3ce8b9cea..0000000000 Binary files a/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events and /dev/null differ diff --git a/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events b/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events deleted file mode 100644 index 2ab0ec469f..0000000000 Binary files a/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events and /dev/null differ diff --git a/events/README.md b/events/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/events/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events b/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events deleted file mode 100644 index d805fc253e..0000000000 Binary files a/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events and /dev/null differ diff --git a/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events b/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events deleted file mode 100644 index 3d67b74ced..0000000000 Binary files a/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events and /dev/null differ diff --git a/flips/README.md b/flips/README.md deleted file mode 100644 index 0c62173b6a..0000000000 --- a/flips/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) diff --git a/flips/pom.xml b/flips/pom.xml deleted file mode 100644 index 75dc8bb579..0000000000 --- a/flips/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - 4.0.0 - flips - flips - 0.0.1-SNAPSHOT - jar - flips - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot-starter-web.version} - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot-starter-test.version} - - - com.github.feature-flip - flips-web - ${flips-web.version} - - - org.projectlombok - lombok - - ${lombok.version} - provided - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - - - - 1.5.10.RELEASE - 1.5.9.RELEASE - 1.0.1 - 1.16.18 - - - diff --git a/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java b/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java deleted file mode 100644 index 7001aeb991..0000000000 --- a/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.flips; - -import org.flips.describe.config.FlipWebContextConfiguration; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; - -@SpringBootApplication -@Import(FlipWebContextConfiguration.class) -public class ApplicationConfig { - - public static void main(String[] args) { - SpringApplication.run(ApplicationConfig.class, args); - } -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/controller/FlipController.java b/flips/src/main/java/com/baeldung/flips/controller/FlipController.java deleted file mode 100644 index 50458023b3..0000000000 --- a/flips/src/main/java/com/baeldung/flips/controller/FlipController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.flips.controller; - -import com.baeldung.flips.model.Foo; -import com.baeldung.flips.service.FlipService; -import org.flips.annotation.FlipOnDateTime; -import org.flips.annotation.FlipOnDaysOfWeek; -import org.flips.annotation.FlipOnEnvironmentProperty; -import org.flips.annotation.FlipOnProfiles; -import org.springframework.beans.factory.annotation.Autowired; -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.RestController; - -import java.time.DayOfWeek; -import java.util.List; - -@RestController -public class FlipController { - - private FlipService flipService; - - @Autowired - public FlipController(FlipService flipService) { - this.flipService = flipService; - } - - @RequestMapping(value = "/foos", method = RequestMethod.GET) - @FlipOnProfiles(activeProfiles = "dev") - public List getAllFoos() { - return flipService.getAllFoos(); - } - - @RequestMapping(value = "/foo/{id}", method = RequestMethod.GET) - @FlipOnDaysOfWeek(daysOfWeek = { - DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, - DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY - }) - public Foo getFooByNewId(@PathVariable int id) { - return flipService.getFooById(id).orElse(new Foo("Not Found", -1)); - } - - @RequestMapping(value = "/foo/last", method = RequestMethod.GET) - @FlipOnDateTime(cutoffDateTimeProperty = "last.active.after") - public Foo getLastFoo() { - return flipService.getLastFoo(); - } - - @RequestMapping(value = "/foo/first", method = RequestMethod.GET) - @FlipOnDateTime(cutoffDateTimeProperty = "first.active.after") - public Foo getFirstFoo() { - return flipService.getLastFoo(); - } - - @RequestMapping(value = "/foos/{id}", method = RequestMethod.GET) - @FlipOnEnvironmentProperty(property = "feature.foo.by.id", expectedValue = "Y") - public Foo getFooById(@PathVariable int id) { - return flipService.getFooById(id).orElse(new Foo("Not Found", -1)); - } - - @RequestMapping(value = "/foo/new", method = RequestMethod.GET) - public Foo getNewThing() { - return flipService.getNewFoo(); - } -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/model/Foo.java b/flips/src/main/java/com/baeldung/flips/model/Foo.java deleted file mode 100644 index be15bee15c..0000000000 --- a/flips/src/main/java/com/baeldung/flips/model/Foo.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.flips.model; - -import lombok.Data; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -@Data -@RequiredArgsConstructor -public class Foo { - @NonNull private final String name; - @NonNull private final int id; -} diff --git a/flips/src/main/java/com/baeldung/flips/service/FlipService.java b/flips/src/main/java/com/baeldung/flips/service/FlipService.java deleted file mode 100644 index 9f7fb325a5..0000000000 --- a/flips/src/main/java/com/baeldung/flips/service/FlipService.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.flips.service; - -import com.baeldung.flips.model.Foo; -import org.flips.annotation.FlipBean; -import org.flips.annotation.FlipOnSpringExpression; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -@Service -public class FlipService { - - private final List foos; - - public FlipService() { - foos = new ArrayList<>(); - foos.add(new Foo("Foo1", 1)); - foos.add(new Foo("Foo2", 2)); - foos.add(new Foo("Foo3", 3)); - foos.add(new Foo("Foo4", 4)); - foos.add(new Foo("Foo5", 5)); - foos.add(new Foo("Foo6", 6)); - - } - - public List getAllFoos() { - return foos; - } - - public Optional getFooById(int id) { - return foos.stream().filter(foo -> (foo.getId() == id)).findFirst(); - } - - @FlipBean(with = NewFlipService.class) - @FlipOnSpringExpression(expression = "(2 + 2) == 4") - public Foo getNewFoo() { - return new Foo("New Foo!", 99); - } - - public Foo getLastFoo() { - return foos.get(foos.size() - 1); - } - - public Foo getFirstFoo() { - return foos.get(0); - } - -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java b/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java deleted file mode 100644 index 1dcda9b6ca..0000000000 --- a/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.flips.service; - -import com.baeldung.flips.model.Foo; -import org.springframework.stereotype.Service; - -@Service -public class NewFlipService { - - public Foo getNewFoo() { - return new Foo("Shiny New Foo!", 100); - } - -} \ No newline at end of file diff --git a/flips/src/main/resources/application.properties b/flips/src/main/resources/application.properties deleted file mode 100644 index 274896be15..0000000000 --- a/flips/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -feature.foo.by.id=Y -feature.new.foo=Y -last.active.after=2018-03-14T00:00:00Z -first.active.after=2999-03-15T00:00:00Z -logging.level.org.flips=info \ No newline at end of file diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java deleted file mode 100644 index 9dd4ef064a..0000000000 --- a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.flips.controller; - -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; - -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "feature.foo.by.id=Y", - "feature.new.foo=Y", - "last.active.after=2018-03-14T00:00:00Z", - "first.active.after=2999-03-15T00:00:00Z", - "logging.level.org.flips=info" - -}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -@ActiveProfiles("dev") -public class FlipControllerIntegrationTest { - - @Autowired private MockMvc mvc; - - @Test - public void givenValidDayOfWeek_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/1")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void givenValidDate_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/last")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6))); - } - - @Test - public void givenInvalidDate_APINotAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/first")) - .andExpect(MockMvcResultMatchers.status().is(501)); - } - - @Test - public void givenCorrectProfile_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6))); - } - - @Test - public void givenPropertySet_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos/1")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void getValidExpression_FlipBean() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/new")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100))); - } -} \ No newline at end of file diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index c6ee26f783..dbb32f1e5a 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/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 - com.baeldung flyway-cdi-extension 1.0-SNAPSHOT + flyway-cdi-extension 1.8 diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/BooleanExample.java b/gson/src/main/java/org/baeldung/gson/primitives/models/BooleanExample.java new file mode 100644 index 0000000000..1fe87650de --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/BooleanExample.java @@ -0,0 +1,9 @@ +package org.baeldung.gson.primitives.models; + +public class BooleanExample { + public boolean value; + + public String toString() { + return "{boolean: " + value + "}"; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/ByteExample.java b/gson/src/main/java/org/baeldung/gson/primitives/models/ByteExample.java new file mode 100644 index 0000000000..2e1c68ee51 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/ByteExample.java @@ -0,0 +1,9 @@ +package org.baeldung.gson.primitives.models; + +public class ByteExample { + public byte value = (byte) 1; + + public String toString() { + return "{byte: " + value + "}"; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/CharExample.java b/gson/src/main/java/org/baeldung/gson/primitives/models/CharExample.java new file mode 100644 index 0000000000..ccac913f23 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/CharExample.java @@ -0,0 +1,9 @@ +package org.baeldung.gson.primitives.models; + +public class CharExample { + public char value; + + public String toString() { + return "{char: " + value + "}"; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/DoubleExample.java b/gson/src/main/java/org/baeldung/gson/primitives/models/DoubleExample.java new file mode 100644 index 0000000000..5022b6a11e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/DoubleExample.java @@ -0,0 +1,9 @@ +package org.baeldung.gson.primitives.models; + +public class DoubleExample { + public double value; + + public String toString() { + return "{float: " + value + "}"; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/FloatExample.java b/gson/src/main/java/org/baeldung/gson/primitives/models/FloatExample.java new file mode 100644 index 0000000000..00a97f68fc --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/FloatExample.java @@ -0,0 +1,9 @@ +package org.baeldung.gson.primitives.models; + +public class FloatExample { + public float value; + + public String toString() { + return "{float: " + value + "}"; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/InfinityValuesExample.java b/gson/src/main/java/org/baeldung/gson/primitives/models/InfinityValuesExample.java new file mode 100644 index 0000000000..163b0a3d95 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/InfinityValuesExample.java @@ -0,0 +1,6 @@ +package org.baeldung.gson.primitives.models; + +public class InfinityValuesExample { + public float negativeInfinity; + public float positiveInfinity; +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/LongExample.java b/gson/src/main/java/org/baeldung/gson/primitives/models/LongExample.java new file mode 100644 index 0000000000..e709650789 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/LongExample.java @@ -0,0 +1,9 @@ +package org.baeldung.gson.primitives.models; + +public class LongExample { + public long value = 1; + + public String toString() { + return "{byte: " + value + "}"; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/PrimitiveBundle.java b/gson/src/main/java/org/baeldung/gson/primitives/models/PrimitiveBundle.java new file mode 100644 index 0000000000..ad7309a2f7 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/PrimitiveBundle.java @@ -0,0 +1,19 @@ +package org.baeldung.gson.primitives.models; + +public class PrimitiveBundle { + public byte byteValue; + public short shortValue; + public int intValue; + public long longValue; + public float floatValue; + public double doubleValue; + public boolean booleanValue; + public char charValue; + + public String toString() { + return "{" + "byte: " + byteValue + ", " + "short: " + shortValue + ", " + + "int: " + intValue + ", " + "long: " + longValue + ", " + + "float: " + floatValue + ", " + "double: " + doubleValue + ", " + + "boolean: " + booleanValue + ", " + "char: " + charValue + "}"; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/primitives/models/PrimitiveBundleInitialized.java b/gson/src/main/java/org/baeldung/gson/primitives/models/PrimitiveBundleInitialized.java new file mode 100644 index 0000000000..2780f7fd18 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/primitives/models/PrimitiveBundleInitialized.java @@ -0,0 +1,18 @@ +package org.baeldung.gson.primitives.models; + +public class PrimitiveBundleInitialized { + // @formatter:off + public byte byteValue = (byte) 1; + public short shortValue = (short) 1; + public int intValue = 1; + public long longValue = 1L; + public float floatValue = 1.0f; + public double doubleValue = 1; + // @formatter:on + + public String toString() { + return "{" + "byte: " + byteValue + ", " + "short: " + shortValue + ", " + + "int: " + intValue + ", " + "long: " + longValue + ", " + + "float: " + floatValue + ", " + "double: " + doubleValue + "}"; + } +} diff --git a/gson/src/test/java/org/baeldung/gson/primitives/PrimitiveValuesUnitTest.java b/gson/src/test/java/org/baeldung/gson/primitives/PrimitiveValuesUnitTest.java new file mode 100644 index 0000000000..7d249bc55c --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/primitives/PrimitiveValuesUnitTest.java @@ -0,0 +1,248 @@ +package org.baeldung.gson.primitives; + +import com.google.gson.*; +import org.baeldung.gson.primitives.models.*; +import org.junit.Test; + +import java.lang.reflect.Type; + +import static junit.framework.TestCase.*; + +public class PrimitiveValuesUnitTest { + @Test public void whenSerializingToJSON_thenShouldCreateJSON() { + PrimitiveBundle primitiveBundle = new PrimitiveBundle(); + + // @formatter:off + primitiveBundle.byteValue = (byte) 0x00001111; + primitiveBundle.shortValue = (short) 3; + primitiveBundle.intValue = 3; + primitiveBundle.longValue = 3; + primitiveBundle.floatValue = 3.5f; + primitiveBundle.doubleValue = 3.5; + primitiveBundle.booleanValue = true; + primitiveBundle.charValue = 'a'; + // @formatter:on + + Gson gson = new Gson(); + + String expected = "{\"byteValue\":17,\"shortValue\":3,\"intValue\":3," + + "\"longValue\":3,\"floatValue\":3.5" + ",\"doubleValue\":3.5" + + ",\"booleanValue\":true,\"charValue\":\"a\"}"; + + assertEquals(expected, gson.toJson(primitiveBundle)); + } + + @Test(expected = IllegalArgumentException.class) public void + whenSerializingInfinity_thenShouldRaiseAnException() { + InfinityValuesExample model = new InfinityValuesExample(); + model.negativeInfinity = Float.NEGATIVE_INFINITY; + model.positiveInfinity = Float.POSITIVE_INFINITY; + + Gson gson = new Gson(); + + gson.toJson(model); + } + + @Test(expected = IllegalArgumentException.class) public void + whenSerializingNaN_thenShouldRaiseAnException() { + FloatExample model = new FloatExample(); + model.value = Float.NaN; + + Gson gson = new Gson(); + gson.toJson(model); + } + + @Test public void whenDeserializingFromJSON_thenShouldParseTheValueInTheString() { + String json = "{\"byteValue\": 17, \"shortValue\": 3, \"intValue\": 3, " + + "\"longValue\": 3, \"floatValue\": 3.5" + ", \"doubleValue\": 3.5" + + ", \"booleanValue\": true, \"charValue\": \"a\"}"; + + Gson gson = new Gson(); + PrimitiveBundle model = gson.fromJson(json, PrimitiveBundle.class); + + // @formatter:off + assertEquals(17, model.byteValue); + assertEquals(3, model.shortValue); + assertEquals(3, model.intValue); + assertEquals(3, model.longValue); + assertEquals(3.5, model.floatValue, 0.0001); + assertEquals(3.5, model.doubleValue, 0.0001); + assertTrue( model.booleanValue); + assertEquals('a', model.charValue); + // @formatter:on + } + + @Test public void whenDeserializingHighPrecissionNumberIntoFloat_thenShouldPerformRounding() { + String json = "{\"value\": 12.123425589123456}"; + Gson gson = new Gson(); + FloatExample model = gson.fromJson(json, FloatExample.class); + assertEquals(12.123426f, model.value, 0.000001); + } + + @Test public void whenDeserializingHighPrecissiongNumberIntoDouble_thenShouldPerformRounding() { + String json = "{\"value\": 12.123425589123556}"; + Gson gson = new Gson(); + DoubleExample model = gson.fromJson(json, DoubleExample.class); + assertEquals(12.123425589124f, model.value, 0.000001); + } + + + @Test public void whenDeserializingValueThatOverflows_thenShouldOverflowSilently() { + Gson gson = new Gson(); + String json = "{\"value\": \"300\"}"; + ByteExample model = gson.fromJson(json, ByteExample.class); + + assertEquals(44, model.value); + } + + @Test public void whenDeserializingRealIntoByte_thenShouldRaiseAnException() { + Gson gson = new Gson(); + String json = "{\"value\": 2.3}"; + try { + gson.fromJson(json, ByteExample.class); + } catch (Exception ex) { + assertTrue(ex instanceof JsonSyntaxException); + assertTrue(ex.getCause() instanceof NumberFormatException); + return; + } + + fail(); + } + + @Test public void whenDeserializingRealIntoLong_thenShouldRaiseAnException() { + Gson gson = new Gson(); + String json = "{\"value\": 2.3}"; + try { + gson.fromJson(json, LongExample.class); + } catch (Exception ex) { + assertTrue(ex instanceof JsonSyntaxException); + assertTrue(ex.getCause() instanceof NumberFormatException); + return; + } + + fail(); + } + + @Test public void whenDeserializingRealWhoseDecimalPartIs0_thenShouldParseItCorrectly() { + Gson gson = new Gson(); + String json = "{\"value\": 2.0}"; + LongExample model = gson.fromJson(json, LongExample.class); + assertEquals(2, model.value); + } + + @Test public void whenDeserializingUnicodeChar_thenShouldParseItCorrectly() { + Gson gson = new Gson(); + String json = "{\"value\": \"\\u00AE\"}"; + CharExample model = gson.fromJson(json, CharExample.class); + + assertEquals('\u00AE', model.value); + } + + @Test public void whenDeserializingNullValues_thenShouldIgnoreThoseFields() { + Gson gson = new Gson(); + // @formatter:off + String json = "{\"byteValue\": null, \"shortValue\": null, " + + "\"intValue\": null, " + "\"longValue\": null, \"floatValue\": null" + + ", \"doubleValue\": null}"; + // @formatter:on + PrimitiveBundleInitialized model = gson.fromJson(json, + PrimitiveBundleInitialized.class); + + assertEquals(1, model.byteValue); + assertEquals(1, model.shortValue); + assertEquals(1, model.intValue); + assertEquals(1, model.longValue); + assertEquals(1, model.floatValue, 0.0001); + assertEquals(1, model.doubleValue, 0.0001); + } + + @Test(expected = JsonSyntaxException.class) public void + whenDeserializingTheEmptyString_thenShouldRaiseAnException() { + Gson gson = new Gson(); + // @formatter:off + String json = "{\"byteValue\": \"\", \"shortValue\": \"\", " + + "\"intValue\": \"\", " + "\"longValue\": \"\", \"floatValue\": \"\"" + + ", \"doubleValue\": \"\"" + ", \"booleanValue\": \"\"}"; + // @formatter:on + gson.fromJson(json, PrimitiveBundleInitialized.class); + } + + @Test public void whenDeserializingTheEmptyStringIntoChar_thenShouldHaveTheEmtpyChar() { + Gson gson = new Gson(); + // @formatter:off + String json = "{\"charValue\": \"\"}"; + // @formatter:on + CharExample model = gson.fromJson(json, CharExample.class); + + assertEquals(Character.MIN_VALUE, model.value); + } + + @Test public void whenDeserializingValidValueAppearingInAString_thenShouldParseTheValue() { + Gson gson = new Gson(); + // @formatter:off + String json = "{\"byteValue\": \"15\", \"shortValue\": \"15\", " + + "\"intValue\": \"15\", " + "\"longValue\": \"15\", \"floatValue\": \"15.0\"" + + ", \"doubleValue\": \"15.0\"}"; + // @formatter:on + PrimitiveBundleInitialized model = gson.fromJson(json, + PrimitiveBundleInitialized.class); + + assertEquals(15, model.byteValue); + assertEquals(15, model.shortValue); + assertEquals(15, model.intValue); + assertEquals(15, model.longValue); + assertEquals(15, model.floatValue, 0.0001); + assertEquals(15, model.doubleValue, 0.0001); + } + + @Test public void whenDeserializingABooleanFrom0Or1Integer_thenShouldRaiseAnException() { + String json = "{\"value\": 1}"; + Gson gson = new Gson(); + + try { + gson.fromJson(json, BooleanExample.class); + } catch (Exception ex) { + assertTrue(ex instanceof JsonSyntaxException); + assertTrue(ex.getCause() instanceof IllegalStateException); + return; + } + + fail(); + } + + @Test public void whenDeserializingWithCustomDeserializerABooleanFrom0Or1Integer_thenShouldWork() { + String json = "{\"value\": 1}"; + GsonBuilder builder = new GsonBuilder(); + builder.registerTypeAdapter(BooleanExample.class, + new BooleanAs2ValueIntegerDeserializer()); + + Gson gson = builder.create(); + + BooleanExample model = gson.fromJson(json, BooleanExample.class); + + assertTrue(model.value); + } + + // @formatter:off + static class BooleanAs2ValueIntegerDeserializer implements JsonDeserializer { + @Override public BooleanExample deserialize( + JsonElement jsonElement, + Type type, + JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + + BooleanExample model = new BooleanExample(); + int value = jsonElement.getAsJsonObject().getAsJsonPrimitive("value").getAsInt(); + if (value == 0) { + model.value = false; + } else if (value == 1) { + model.value = true; + } else { + throw new JsonParseException("Unexpected value. Trying to deserialize " + + "a boolean from an integer different than 0 and 1."); + } + + return model; + } + } + // @formatter:on +} diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml index ce9395fbf4..d55aa9ce82 100644 --- a/guava-modules/guava-18/pom.xml +++ b/guava-modules/guava-18/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - com.baeldung guava-18 0.1.0-SNAPSHOT - + guava-18 + com.baeldung parent-java diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml index 5dfb4d2cec..0548bb0c1f 100644 --- a/guava-modules/guava-19/pom.xml +++ b/guava-modules/guava-19/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - com.baeldung guava-19 0.1.0-SNAPSHOT - + guava-19 + com.baeldung parent-java diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml index 945b7c27c1..bdb1058a48 100644 --- a/guava-modules/guava-21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -4,7 +4,8 @@ 4.0.0 guava-21 1.0-SNAPSHOT - + guava-21 + com.baeldung parent-java diff --git a/guava/README.md b/guava/README.md index 56e6aff50c..60754dbe57 100644 --- a/guava/README.md +++ b/guava/README.md @@ -17,3 +17,4 @@ - [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream) - [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) - [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter) +- [Hamcrest File Matchers](https://www.baeldung.com/hamcrest-file-matchers) diff --git a/guava/src/test/java/org/baeldung/hamcrest/README.md b/guava/src/test/java/org/baeldung/hamcrest/README.md index 456108d78a..7266ecda3a 100644 --- a/guava/src/test/java/org/baeldung/hamcrest/README.md +++ b/guava/src/test/java/org/baeldung/hamcrest/README.md @@ -1,3 +1,2 @@ ### Relevant Articles: - [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide) -- [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers) diff --git a/guest/core-java-9/pom.xml b/guest/core-java-9/pom.xml index e9271b42ff..3847c19d16 100644 --- a/guest/core-java-9/pom.xml +++ b/guest/core-java-9/pom.xml @@ -4,7 +4,8 @@ com.stackify core-java-9 0.0.1-SNAPSHOT - + core-java-9 + com.baeldung parent-modules diff --git a/guest/core-java/pom.xml b/guest/core-java/pom.xml index 787dd764a1..5057f7eaed 100644 --- a/guest/core-java/pom.xml +++ b/guest/core-java/pom.xml @@ -4,6 +4,7 @@ com.stackify core-java 0.0.1-SNAPSHOT + core-java com.baeldung diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml index 6b189143a4..a57dd28ffd 100644 --- a/guest/core-kotlin/pom.xml +++ b/guest/core-kotlin/pom.xml @@ -6,7 +6,8 @@ 1.0-SNAPSHOT com.stackify jar - + core-kotlin + jcenter diff --git a/guest/deep-jsf/pom.xml b/guest/deep-jsf/pom.xml index e09b5e0606..12426a8833 100644 --- a/guest/deep-jsf/pom.xml +++ b/guest/deep-jsf/pom.xml @@ -4,6 +4,7 @@ com.stackify deep-jsf 0.0.1-SNAPSHOT + deep-jsf war diff --git a/guest/junit5-example/pom.xml b/guest/junit5-example/pom.xml index 457fb1fcaa..7c0cc3e776 100644 --- a/guest/junit5-example/pom.xml +++ b/guest/junit5-example/pom.xml @@ -4,7 +4,8 @@ junit5-example junit5-example 0.0.1-SNAPSHOT - + junit5-example + com.baeldung parent-modules diff --git a/guest/log4j2-example/pom.xml b/guest/log4j2-example/pom.xml index f64869879f..045ff7325b 100644 --- a/guest/log4j2-example/pom.xml +++ b/guest/log4j2-example/pom.xml @@ -4,7 +4,8 @@ log4j2-example log4j2-example 0.0.1-SNAPSHOT - + log4j2-example + com.baeldung parent-modules @@ -40,7 +41,7 @@ - 2.8.8.1 + 2.9.7 2.8.2 diff --git a/guest/logback-example/pom.xml b/guest/logback-example/pom.xml index 04de6a00a2..6e9fe0ddea 100644 --- a/guest/logback-example/pom.xml +++ b/guest/logback-example/pom.xml @@ -4,6 +4,7 @@ com.stackify logback-example 0.0.1-SNAPSHOT + logback-example com.baeldung diff --git a/guest/memory-leaks/pom.xml b/guest/memory-leaks/pom.xml index 956ae9c408..f1d411acbc 100644 --- a/guest/memory-leaks/pom.xml +++ b/guest/memory-leaks/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung memory-leaks 0.0.1-SNAPSHOT - + memory-leaks + com.baeldung parent-modules diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml index 974421de97..07b9cc49d8 100644 --- a/guest/remote-debugging/pom.xml +++ b/guest/remote-debugging/pom.xml @@ -5,8 +5,8 @@ com.stackify remote-debugging 0.0.1-SNAPSHOT + remote-debugging war - remote-debugging org.springframework.boot diff --git a/guest/slf4j/guide/pom.xml b/guest/slf4j/guide/pom.xml index 0db9b46247..657ede73b6 100644 --- a/guest/slf4j/guide/pom.xml +++ b/guest/slf4j/guide/pom.xml @@ -2,13 +2,12 @@ 4.0.0 - com.stackify.slf4j.guide slf4j-parent-module 1.0.0-SNAPSHOT + slf4j-parent-module pom - org.springframework.boot spring-boot-starter-parent diff --git a/guest/slf4j/guide/slf4j-log4j/pom.xml b/guest/slf4j/guide/slf4j-log4j/pom.xml index 0d08fa6191..bca5392f4d 100644 --- a/guest/slf4j/guide/slf4j-log4j/pom.xml +++ b/guest/slf4j/guide/slf4j-log4j/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - slf4j-log4j 0.0.1-SNAPSHOT + slf4j-log4j jar diff --git a/guest/slf4j/guide/slf4j-log4j2/pom.xml b/guest/slf4j/guide/slf4j-log4j2/pom.xml index 643649335f..9473362cb8 100644 --- a/guest/slf4j/guide/slf4j-log4j2/pom.xml +++ b/guest/slf4j/guide/slf4j-log4j2/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - slf4j-log4j2 0.0.1-SNAPSHOT + slf4j-log4j2 jar diff --git a/guest/slf4j/guide/slf4j-logback/pom.xml b/guest/slf4j/guide/slf4j-logback/pom.xml index e8aebf0ef6..0327e79732 100644 --- a/guest/slf4j/guide/slf4j-logback/pom.xml +++ b/guest/slf4j/guide/slf4j-logback/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - slf4j-logback 0.0.1-SNAPSHOT + slf4j-logback jar diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml index 7daa8f668e..423dadbb99 100644 --- a/guest/spring-boot-app/pom.xml +++ b/guest/spring-boot-app/pom.xml @@ -4,6 +4,7 @@ spring-boot-app spring-boot-app 0.0.1-SNAPSHOT + spring-boot-app war diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index c0ef451605..3bffb1530d 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -5,8 +5,8 @@ com.stackify.guest spring-mvc 0.0.1-SNAPSHOT - jar spring-mvc + jar Spring MVC sample project diff --git a/guest/thread-pools/pom.xml b/guest/thread-pools/pom.xml index db9a5ac89f..2591cb2746 100644 --- a/guest/thread-pools/pom.xml +++ b/guest/thread-pools/pom.xml @@ -4,7 +4,8 @@ com.stackify thread-pools 0.0.1-SNAPSHOT - + thread-pools + com.baeldung parent-modules diff --git a/guest/tomcat-app/pom.xml b/guest/tomcat-app/pom.xml index 7fd27e869b..9ce77c758a 100644 --- a/guest/tomcat-app/pom.xml +++ b/guest/tomcat-app/pom.xml @@ -4,6 +4,7 @@ com.stackify tomcat-app 0.0.1-SNAPSHOT + tomcat-app war diff --git a/guest/webservices/rest-client/pom.xml b/guest/webservices/rest-client/pom.xml index 5e52b7161c..8508186e86 100644 --- a/guest/webservices/rest-client/pom.xml +++ b/guest/webservices/rest-client/pom.xml @@ -3,6 +3,7 @@ com.stackify rest-client 0.0.1-SNAPSHOT + rest-client war diff --git a/guest/webservices/rest-server/pom.xml b/guest/webservices/rest-server/pom.xml index 4b3d241293..c576924215 100644 --- a/guest/webservices/rest-server/pom.xml +++ b/guest/webservices/rest-server/pom.xml @@ -4,6 +4,7 @@ com.stackify rest-server 0.0.1-SNAPSHOT + rest-server war diff --git a/guest/webservices/spring-rest-service/pom.xml b/guest/webservices/spring-rest-service/pom.xml index 49d35766e8..fcec8a3e12 100644 --- a/guest/webservices/spring-rest-service/pom.xml +++ b/guest/webservices/spring-rest-service/pom.xml @@ -4,6 +4,7 @@ com.stackify spring-rest-service 0.0.1-SNAPSHOT + spring-rest-service war diff --git a/helidon/helidon-mp/pom.xml b/helidon/helidon-mp/pom.xml index 1ec1131a67..1f39431886 100644 --- a/helidon/helidon-mp/pom.xml +++ b/helidon/helidon-mp/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - helidon-mp - + helidon-mp + com.baeldung.helidon helidon diff --git a/helidon/helidon-se/pom.xml b/helidon/helidon-se/pom.xml index 5e14ecb81c..8982bf048e 100644 --- a/helidon/helidon-se/pom.xml +++ b/helidon/helidon-se/pom.xml @@ -3,9 +3,9 @@ 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 - helidon-se - + helidon-se + com.baeldung.helidon helidon diff --git a/helidon/pom.xml b/helidon/pom.xml index ea8cc52ee0..85bab4db42 100644 --- a/helidon/pom.xml +++ b/helidon/pom.xml @@ -2,10 +2,9 @@ 4.0.0 - com.baeldung.helidon helidon - 1.0.0-SNAPSHOT + helidon pom diff --git a/image-processing/pom.xml b/image-processing/pom.xml index fe8001ae3a..ce75145dc7 100644 --- a/image-processing/pom.xml +++ b/image-processing/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - com.baeldung image-processing 1.0-SNAPSHOT - + image-processing + com.baeldung parent-modules diff --git a/immutables/pom.xml b/immutables/pom.xml index 17510690b0..efb21e584a 100644 --- a/immutables/pom.xml +++ b/immutables/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 immutables - 1.0.0-SNAPSHOT - + immutables + com.baeldung parent-modules diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductJsonAnySetter.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductJsonAnySetter.java new file mode 100644 index 0000000000..13c21e37af --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductJsonAnySetter.java @@ -0,0 +1,39 @@ +package com.baeldung.jackson.deserialization.dynamicobject; + +import java.util.LinkedHashMap; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonAnySetter; + +public class ProductJsonAnySetter { + + private String name; + private String category; + private Map details = new LinkedHashMap<>(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Map getDetails() { + return details; + } + + @JsonAnySetter + public void setDetail(String key, Object value) { + details.put(key, value); + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductJsonNode.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductJsonNode.java new file mode 100644 index 0000000000..729d542df3 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductJsonNode.java @@ -0,0 +1,35 @@ +package com.baeldung.jackson.deserialization.dynamicobject; + +import com.fasterxml.jackson.databind.JsonNode; + +public class ProductJsonNode { + + private String name; + private String category; + private JsonNode details; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public JsonNode getDetails() { + return details; + } + + public void setDetails(JsonNode details) { + this.details = details; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductMap.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductMap.java new file mode 100644 index 0000000000..65d225f49b --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/dynamicobject/ProductMap.java @@ -0,0 +1,35 @@ +package com.baeldung.jackson.deserialization.dynamicobject; + +import java.util.Map; + +public class ProductMap { + + private String name; + private String category; + private Map details; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Map getDetails() { + return details; + } + + public void setDetails(Map details) { + this.details = details; + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/dynamicobject/DynamicObjectDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/dynamicobject/DynamicObjectDeserializationUnitTest.java new file mode 100644 index 0000000000..d49677c1a2 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/dynamicobject/DynamicObjectDeserializationUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.jackson.deserialization.dynamicobject; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.Scanner; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class DynamicObjectDeserializationUnitTest { + + private ObjectMapper objectMapper; + + @BeforeEach + void setup() { + objectMapper = new ObjectMapper(); + } + + private String readResource(String path) { + try (Scanner scanner = new Scanner(getClass().getResourceAsStream(path), "UTF-8")) { + return scanner.useDelimiter("\\A").next(); + } + } + + @Test + void givenJsonString_whenParsingToJsonNode_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException { + // given + String json = readResource("/deserialize-dynamic-object/embedded.json"); + + // when + ProductJsonNode product = objectMapper.readValue(json, ProductJsonNode.class); + + // then + assertThat(product.getName()).isEqualTo("Pear yPhone 72"); + assertThat(product.getDetails().get("audioConnector").asText()).isEqualTo("none"); + } + + @Test + void givenJsonString_whenParsingToMap_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException { + // given + String json = readResource("/deserialize-dynamic-object/embedded.json"); + + // when + ProductMap product = objectMapper.readValue(json, ProductMap.class); + + // then + assertThat(product.getName()).isEqualTo("Pear yPhone 72"); + assertThat(product.getDetails().get("audioConnector")).isEqualTo("none"); + } + + @Test + void givenJsonString_whenParsingWithJsonAnySetter_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException { + // given + String json = readResource("/deserialize-dynamic-object/flat.json"); + + // when + ProductJsonAnySetter product = objectMapper.readValue(json, ProductJsonAnySetter.class); + + // then + assertThat(product.getName()).isEqualTo("Pear yPhone 72"); + assertThat(product.getDetails().get("audioConnector")).isEqualTo("none"); + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java index 390030d0d4..672ff5c6fd 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDateUnitTest.java @@ -11,7 +11,6 @@ import java.time.LocalDateTime; import java.util.Date; import java.util.TimeZone; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Test; @@ -24,8 +23,9 @@ import com.baeldung.jackson.date.EventWithSerializer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.util.StdDateFormat; import com.fasterxml.jackson.datatype.joda.JodaModule; -import com.fasterxml.jackson.datatype.jsr310.JSR310Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class JacksonDateUnitTest { @@ -54,10 +54,12 @@ public class JacksonDateUnitTest { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.setDateFormat(new ISO8601DateFormat()); + + // StdDateFormat is ISO8601 since jackson 2.9 + mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true)); final String result = mapper.writeValueAsString(event); - assertThat(result, containsString("1970-01-01T02:30:00Z")); + assertThat(result, containsString("1970-01-01T02:30:00.000+00:00")); } @Test @@ -152,7 +154,7 @@ public class JacksonDateUnitTest { final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30); final ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JSR310Module()); + mapper.registerModule(new JavaTimeModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); final String result = mapper.writeValueAsString(date); diff --git a/jackson/src/test/resources/deserialize-dynamic-object/embedded.json b/jackson/src/test/resources/deserialize-dynamic-object/embedded.json new file mode 100644 index 0000000000..e4f11f7f1f --- /dev/null +++ b/jackson/src/test/resources/deserialize-dynamic-object/embedded.json @@ -0,0 +1,8 @@ +{ + "name": "Pear yPhone 72", + "category": "cellphone", + "details": { + "displayAspectRatio": "97:3", + "audioConnector": "none" + } +} \ No newline at end of file diff --git a/jackson/src/test/resources/deserialize-dynamic-object/flat.json b/jackson/src/test/resources/deserialize-dynamic-object/flat.json new file mode 100644 index 0000000000..799ea9339d --- /dev/null +++ b/jackson/src/test/resources/deserialize-dynamic-object/flat.json @@ -0,0 +1,6 @@ +{ + "name": "Pear yPhone 72", + "category": "cellphone", + "displayAspectRatio": "97:3", + "audioConnector": "none" +} \ No newline at end of file diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index 761a78d7b0..31fead3c42 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -8,4 +8,6 @@ - [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list) - [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set) - [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string) -- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) \ No newline at end of file +- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) +- [Array to String Conversions](https://www.baeldung.com/java-array-to-string) +- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) \ No newline at end of file diff --git a/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java b/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java new file mode 100644 index 0000000000..b563475997 --- /dev/null +++ b/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java @@ -0,0 +1,136 @@ +package org.baeldung.convertarraytostring; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; + +public class ArrayToStringUnitTest { + + // convert with Java + + @Test + public void givenAStringArray_whenConvertBeforeJava8_thenReturnString() { + + String[] strArray = { "Convert", "Array", "With", "Java" }; + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < strArray.length; i++) { + stringBuilder.append(strArray[i]); + } + String joinedString = stringBuilder.toString(); + + assertThat(joinedString, instanceOf(String.class)); + assertEquals("ConvertArrayWithJava", joinedString); + } + + @Test + public void givenAString_whenConvertBeforeJava8_thenReturnStringArray() { + + String input = "lorem ipsum dolor sit amet"; + String[] strArray = input.split(" "); + + assertThat(strArray, instanceOf(String[].class)); + assertEquals(5, strArray.length); + + input = "loremipsum"; + strArray = input.split(""); + assertThat(strArray, instanceOf(String[].class)); + assertEquals(10, strArray.length); + } + + @Test + public void givenAnIntArray_whenConvertBeforeJava8_thenReturnString() { + + int[] strArray = { 1, 2, 3, 4, 5 }; + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < strArray.length; i++) { + stringBuilder.append(Integer.valueOf(strArray[i])); + } + String joinedString = stringBuilder.toString(); + + assertThat(joinedString, instanceOf(String.class)); + assertEquals("12345", joinedString); + } + + // convert with Java Stream API + + @Test + public void givenAStringArray_whenConvertWithJavaStream_thenReturnString() { + + String[] strArray = { "Convert", "With", "Java", "Streams" }; + String joinedString = Arrays.stream(strArray) + .collect(Collectors.joining()); + assertThat(joinedString, instanceOf(String.class)); + assertEquals("ConvertWithJavaStreams", joinedString); + + joinedString = Arrays.stream(strArray) + .collect(Collectors.joining(",")); + assertThat(joinedString, instanceOf(String.class)); + assertEquals("Convert,With,Java,Streams", joinedString); + } + + + // convert with Apache Commons + + @Test + public void givenAStringArray_whenConvertWithApacheCommons_thenReturnString() { + + String[] strArray = { "Convert", "With", "Apache", "Commons" }; + String joinedString = StringUtils.join(strArray); + + assertThat(joinedString, instanceOf(String.class)); + assertEquals("ConvertWithApacheCommons", joinedString); + } + + @Test + public void givenAString_whenConvertWithApacheCommons_thenReturnStringArray() { + + String input = "lorem ipsum dolor sit amet"; + String[] strArray = StringUtils.split(input, " "); + + assertThat(strArray, instanceOf(String[].class)); + assertEquals(5, strArray.length); + } + + + // convert with Guava + + @Test + public void givenAStringArray_whenConvertWithGuava_thenReturnString() { + + String[] strArray = { "Convert", "With", "Guava", null }; + String joinedString = Joiner.on("") + .skipNulls() + .join(strArray); + + assertThat(joinedString, instanceOf(String.class)); + assertEquals("ConvertWithGuava", joinedString); + } + + + @Test + public void givenAString_whenConvertWithGuava_thenReturnStringArray() { + + String input = "lorem ipsum dolor sit amet"; + + List resultList = Splitter.on(' ') + .trimResults() + .omitEmptyStrings() + .splitToList(input); + String[] strArray = resultList.toArray(new String[0]); + + assertThat(strArray, instanceOf(String[].class)); + assertEquals(5, strArray.length); + } +} diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/ImmutableMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/ImmutableMapUnitTest.java new file mode 100644 index 0000000000..b239ae07d8 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/ImmutableMapUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.java.map; + +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.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.ImmutableMap; + + +public class ImmutableMapUnitTest { + + @Test + public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() { + + Map mutableMap = new HashMap<>(); + mutableMap.put("USA", "North America"); + + Map unmodifiableMap = Collections.unmodifiableMap(mutableMap); + assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America")); + + mutableMap.remove("USA"); + assertFalse(unmodifiableMap.containsKey("USA")); + + mutableMap.put("Mexico", "North America"); + assertTrue(unmodifiableMap.containsKey("Mexico")); + } + + @Test + @SuppressWarnings("deprecation") + public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { + + Map mutableMap = new HashMap<>(); + mutableMap.put("USA", "North America"); + + ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap); + assertTrue(immutableMap.containsKey("USA")); + + assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); + + mutableMap.remove("USA"); + assertTrue(immutableMap.containsKey("USA")); + + mutableMap.put("Mexico", "North America"); + assertFalse(immutableMap.containsKey("Mexico")); + } + + @Test + @SuppressWarnings("deprecation") + public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { + + Map mutableMap = new HashMap<>(); + mutableMap.put("USA", "North America"); + + ImmutableMap immutableMap = ImmutableMap.builder() + .putAll(mutableMap) + .put("Costa Rica", "North America") + .build(); + assertTrue(immutableMap.containsKey("USA")); + assertTrue(immutableMap.containsKey("Costa Rica")); + + assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); + + mutableMap.remove("USA"); + assertTrue(immutableMap.containsKey("USA")); + + mutableMap.put("Mexico", "North America"); + assertFalse(immutableMap.containsKey("Mexico")); + } + + @Test + @SuppressWarnings("deprecation") + public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { + + ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America"); + assertTrue(immutableMap.containsKey("USA")); + assertTrue(immutableMap.containsKey("Costa Rica")); + + assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); + } + +} diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java new file mode 100644 index 0000000000..e8aa12d4bd --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java @@ -0,0 +1,228 @@ +package com.baeldung.java.map.compare; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.hamcrest.collection.IsMapContaining.hasKey; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +import com.google.common.base.Equivalence; +import com.google.common.collect.MapDifference; +import com.google.common.collect.MapDifference.ValueDifference; +import com.google.common.collect.Maps; + +public class HashMapComparisonUnitTest { + + Map asiaCapital1; + Map asiaCapital2; + Map asiaCapital3; + + Map asiaCity1; + Map asiaCity2; + Map asiaCity3; + + @Before + public void setup(){ + asiaCapital1 = new HashMap(); + asiaCapital1.put("Japan", "Tokyo"); + asiaCapital1.put("South Korea", "Seoul"); + + asiaCapital2 = new HashMap(); + asiaCapital2.put("South Korea", "Seoul"); + asiaCapital2.put("Japan", "Tokyo"); + + asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("China", "Beijing"); + + asiaCity1 = new HashMap(); + asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" }); + + asiaCity2 = new HashMap(); + asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" }); + asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" }); + + asiaCity3 = new HashMap(); + asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" }); + } + + @Test + public void whenCompareTwoHashMapsUsingEquals_thenSuccess() { + assertTrue(asiaCapital1.equals(asiaCapital2)); + assertFalse(asiaCapital1.equals(asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() { + assertFalse(asiaCity1.equals(asiaCity2)); + } + + @Test + public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() { + assertTrue(areEqual(asiaCapital1, asiaCapital2)); + assertFalse(areEqual(asiaCapital1, asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() { + assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2)); + assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3)); + } + + @Test + public void whenCompareTwoHashMapKeys_thenSuccess() { + assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet())); + assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet())); + } + + @Test + public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() { + Map asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("South Korea", "Seoul"); + asiaCapital3.put("China", "Beijing"); + + Map asiaCapital4 = new HashMap(); + asiaCapital4.put("South Korea", "Seoul"); + asiaCapital4.put("Japan", "Osaka"); + asiaCapital4.put("China", "Beijing"); + + Map result = areEqualKeyValues(asiaCapital3, asiaCapital4); + + assertEquals(3, result.size()); + assertThat(result, hasEntry("Japan", false)); + assertThat(result, hasEntry("South Korea", true)); + assertThat(result, hasEntry("China", true)); + } + + @Test + public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map> entriesDiffering = diff.entriesDiffering(); + + assertFalse(diff.areEqual()); + assertEquals(1, entriesDiffering.size()); + assertThat(entriesDiffering, hasKey("India")); + assertEquals("New Delhi", entriesDiffering.get("India").leftValue()); + assertEquals("Delhi", entriesDiffering.get("India").rightValue()); + } + + @Test + public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesOnlyOnRight = diff.entriesOnlyOnRight(); + Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft(); + + assertEquals(1, entriesOnlyOnRight.size()); + assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing")); + assertEquals(1, entriesOnlyOnLeft.size()); + assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul")); + } + + @Test + public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesInCommon = diff.entriesInCommon(); + + assertEquals(1, entriesInCommon.size()); + assertThat(entriesInCommon, hasEntry("Japan", "Tokyo")); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() { + MapDifference diff = Maps.difference(asiaCity1, asiaCity2); + assertFalse(diff.areEqual()); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() { + Equivalence eq = new Equivalence() { + @Override + protected boolean doEquivalent(String[] a, String[] b) { + return Arrays.equals(a, b); + } + + @Override + protected int doHash(String[] value) { + return value.hashCode(); + } + }; + + MapDifference diff = Maps.difference(asiaCity1, asiaCity2, eq); + assertTrue(diff.areEqual()); + + diff = Maps.difference(asiaCity1, asiaCity3, eq); + assertFalse(diff.areEqual()); + } + + // =========================================================================== + + private boolean areEqual(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> e.getValue() + .equals(second.get(e.getKey()))); + } + + private boolean areEqualWithArrayValue(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey()))); + } + + private Map areEqualKeyValues(Map first, Map second) { + return first.entrySet() + .stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey())))); + } + +} diff --git a/java-dates/README.md b/java-dates/README.md index 66046b16a6..ac3166d938 100644 --- a/java-dates/README.md +++ b/java-dates/README.md @@ -24,3 +24,7 @@ - [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) - [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter) - [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string) +- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp) +- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp) +- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format) +- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) \ No newline at end of file diff --git a/java-dates/src/main/java/com/baeldung/datetime/README.md b/java-dates/src/main/java/com/baeldung/datetime/README.md index 1e4adbb612..7d843af9ea 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/README.md +++ b/java-dates/src/main/java/com/baeldung/datetime/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java b/java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java rename to java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java b/java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java rename to java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java diff --git a/core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java b/java-dates/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java rename to java-dates/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java diff --git a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 92da22cc95..a35699e469 100644 --- a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -8,6 +8,9 @@ import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Locale; import java.util.TimeZone; @@ -51,6 +54,16 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime tenSecondsLater = now.plusSeconds(10); + + long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater); + + assertEquals(diff, 10); + } + @Test public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() { LocalDateTime ldt = LocalDateTime.now(); @@ -60,6 +73,16 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoDateTimesInJava8_whenDifferentiatingInSecondsUsingUntil_thenWeGetTen() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime tenSecondsLater = now.plusSeconds(10); + + long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS); + + assertEquals(diff, 10); + } + @Test public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { org.joda.time.LocalDate now = org.joda.time.LocalDate.now(); diff --git a/core-java/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java b/java-dates/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java rename to java-dates/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java b/java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java rename to java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java b/java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java rename to java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java b/java-dates/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java rename to java-dates/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java diff --git a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml index 6ecc9f7e80..cf92fe2ecd 100644 --- a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml +++ b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - app-auth-basic-store-db + app-auth-basic-store-db war diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml index bf5315e993..43809f1cd5 100644 --- a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - app-auth-custom-form-store-custom + app-auth-custom-form-store-custom war diff --git a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml index c05c0f19be..f9d63f8623 100644 --- a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml +++ b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - app-auth-custom-no-store + app-auth-custom-no-store war 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 570b36add5..6a7b97b2d7 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 @@ -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 - app-auth-form-store-ldap + app-auth-form-store-ldap war diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml index 7546839492..ad33c74ad3 100644 --- a/java-ee-8-security-api/pom.xml +++ b/java-ee-8-security-api/pom.xml @@ -5,6 +5,7 @@ 4.0.0 java-ee-8-security-api 1.0-SNAPSHOT + java-ee-8-security-api pom diff --git a/java-lite/pom.xml b/java-lite/pom.xml index 5111cd2e7f..b261e521a1 100644 --- a/java-lite/pom.xml +++ b/java-lite/pom.xml @@ -5,6 +5,7 @@ org.baeldung java-lite 1.0-SNAPSHOT + java-lite war @@ -94,7 +95,7 @@ 1.15 5.1.45 1.7.0 - 1.8.2 + 2.9.7 1.15 diff --git a/java-numbers/README.md b/java-numbers/README.md index 1138d9a74c..2b1131f325 100644 --- a/java-numbers/README.md +++ b/java-numbers/README.md @@ -13,3 +13,9 @@ - [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) +- [Calculate the Area of a Circle in Java](https://www.baeldung.com/java-calculate-circle-area) +- [A Guide to the Java Math Class](https://www.baeldung.com/java-lang-math) \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/area/circle/Circle.java b/java-numbers/src/main/java/com/baeldung/area/circle/Circle.java similarity index 100% rename from core-java/src/main/java/com/baeldung/area/circle/Circle.java rename to java-numbers/src/main/java/com/baeldung/area/circle/Circle.java diff --git a/core-java/src/main/java/com/baeldung/area/circle/CircleArea.java b/java-numbers/src/main/java/com/baeldung/area/circle/CircleArea.java similarity index 100% rename from core-java/src/main/java/com/baeldung/area/circle/CircleArea.java rename to java-numbers/src/main/java/com/baeldung/area/circle/CircleArea.java diff --git a/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java b/java-numbers/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java similarity index 100% rename from core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java rename to java-numbers/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java diff --git a/core-java/src/main/java/com/baeldung/nth/root/main/Main.java b/java-numbers/src/main/java/com/baeldung/nth/root/main/Main.java similarity index 100% rename from core-java/src/main/java/com/baeldung/nth/root/main/Main.java rename to java-numbers/src/main/java/com/baeldung/nth/root/main/Main.java diff --git a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java b/java-numbers/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java rename to java-numbers/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/java/math/MathUnitTest.java b/java-numbers/src/test/java/com/baeldung/java/math/MathUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/java/math/MathUnitTest.java rename to java-numbers/src/test/java/com/baeldung/java/math/MathUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java b/java-numbers/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java rename to java-numbers/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java b/java-numbers/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java rename to java-numbers/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java b/java-numbers/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java rename to java-numbers/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsManualTest.java diff --git a/core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java b/java-numbers/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java rename to java-numbers/src/test/java/com/baeldung/removingdecimals/RemovingDecimalsUnitTest.java diff --git a/java-rmi/pom.xml b/java-rmi/pom.xml index 33931baedf..ad413b66ab 100644 --- a/java-rmi/pom.xml +++ b/java-rmi/pom.xml @@ -4,6 +4,7 @@ com.baeldung.rmi java-rmi 1.0-SNAPSHOT + java-rmi jar diff --git a/java-spi/exchange-rate-api/pom.xml b/java-spi/exchange-rate-api/pom.xml index b626916b56..fd3a7ae0a7 100644 --- a/java-spi/exchange-rate-api/pom.xml +++ b/java-spi/exchange-rate-api/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 exchange-rate-api + exchange-rate-api jar diff --git a/java-spi/exchange-rate-app/pom.xml b/java-spi/exchange-rate-app/pom.xml index a42a30ceda..7a076d560c 100644 --- a/java-spi/exchange-rate-app/pom.xml +++ b/java-spi/exchange-rate-app/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 exchange-rate-app + exchange-rate-app jar diff --git a/java-spi/exchange-rate-impl/pom.xml b/java-spi/exchange-rate-impl/pom.xml index 41c874c659..8a77b51793 100644 --- a/java-spi/exchange-rate-impl/pom.xml +++ b/java-spi/exchange-rate-impl/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 exchange-rate-impl + exchange-rate-impl jar diff --git a/java-spi/pom.xml b/java-spi/pom.xml index 9ac87bf960..97a22024bd 100644 --- a/java-spi/pom.xml +++ b/java-spi/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-spi + java-spi pom diff --git a/java-streams/pom.xml b/java-streams/pom.xml index e4670c268d..2b52ebb4b3 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-streams 0.1.0-SNAPSHOT @@ -74,6 +74,11 @@ aspectjweaver ${asspectj.version} + + pl.touk + throwing-function + ${throwing-function.version} + @@ -108,8 +113,9 @@ 1.15 0.6.5 2.10 + 1.3 - 3.6.1 + 3.11.1 1.8.9 diff --git a/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java new file mode 100644 index 0000000000..49da6e7175 --- /dev/null +++ b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.stream.filter; + +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class Customer { + private String name; + private int points; + private String profilePhotoUrl; + + public Customer(String name, int points) { + this(name, points, ""); + } + + public Customer(String name, int points, String profilePhotoUrl) { + this.name = name; + this.points = points; + this.profilePhotoUrl = profilePhotoUrl; + } + + public String getName() { + return name; + } + + public int getPoints() { + return points; + } + + public boolean hasOver(int points) { + return this.points > points; + } + + public boolean hasOverThousandPoints() { + return this.points > 100; + } + + public boolean hasValidProfilePhoto() throws IOException { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } + + public boolean hasValidProfilePhotoWithoutCheckedException() { + try { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java new file mode 100644 index 0000000000..cf82802940 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.stream.filter; + +import org.junit.jupiter.api.Test; +import pl.touk.throwing.ThrowingPredicate; +import pl.touk.throwing.exception.WrappedException; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +public class StreamFilterUnitTest { + + @Test + public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List customersWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100) + .collect(Collectors.toList()); + + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); + } + + @Test + public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List charlesWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100 && c + .getName() + .startsWith("Charles")) + .collect(Collectors.toList()); + + assertThat(charlesWithMoreThan100Points).hasSize(1); + assertThat(charlesWithMoreThan100Points).contains(charles); + } + + @Test + public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List customersWithMoreThan100Points = customers + .stream() + .filter(Customer::hasOverThousandPoints) + .collect(Collectors.toList()); + + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); + } + + @Test + public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() { + Optional john = Optional.of(new Customer("John P.", 15)); + Optional sarah = Optional.of(new Customer("Sarah M.", 200)); + Optional mary = Optional.of(new Customer("Mary T.", 300)); + List> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty()); + + List customersWithMoreThan100Points = customers + .stream() + .flatMap(c -> c + .map(Stream::of) + .orElseGet(Stream::empty)) + .filter(Customer::hasOverThousandPoints) + .collect(Collectors.toList()); + + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get()); + } + + @Test + public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() { + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); + + assertThatThrownBy(() -> customers + .stream() + .filter(Customer::hasValidProfilePhotoWithoutCheckedException) + .count()).isInstanceOf(RuntimeException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() { + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); + + assertThatThrownBy(() -> customers + .stream() + .filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto))) + .collect(Collectors.toList())).isInstanceOf(WrappedException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() { + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); + + List customersWithValidProfilePhoto = customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + //handle exception + } + return false; + }) + .collect(Collectors.toList()); + + assertThat(customersWithValidProfilePhoto).hasSize(2); + assertThat(customersWithValidProfilePhoto).contains(john, mary); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .collect(Collectors.toList())).isInstanceOf(RuntimeException.class); + } +} diff --git a/java-strings/README.md b/java-strings/README.md index 2847a0d0a8..fa048dbb5a 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -2,7 +2,7 @@ ## Java Strings Cookbooks and Examples -### Relevant Articles: +### Relevant Articles: - [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) - [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) - [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) @@ -10,7 +10,7 @@ - [Java – Generate Random String](http://www.baeldung.com/java-random-string) - [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) - [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) -- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions) +- [Java String Conversions](https://www.baeldung.com/java-string-conversions) - [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) - [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) - [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) @@ -27,7 +27,6 @@ - [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) - [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) - [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string) -- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [Get Substring from String in Java](https://www.baeldung.com/java-substring) - [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string) - [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) @@ -35,5 +34,16 @@ - [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [String Performance Hints](https://www.baeldung.com/java-string-performance) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) +- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) - [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) - [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) +- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) +- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) +- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) +- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) +- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) +- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) +- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) +- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list) +- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) +- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) \ No newline at end of file diff --git a/java-strings/pom.xml b/java-strings/pom.xml index ab94c28d4d..f4fb1c0865 100755 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -122,13 +122,13 @@ - 3.5 + 3.8.1 1.10 3.6.1 1.19 61.1 - 26.0-jre + 27.0.1-jre diff --git a/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java similarity index 100% rename from core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java rename to java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java diff --git a/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java b/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java new file mode 100644 index 0000000000..2cc67f0b51 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java @@ -0,0 +1,29 @@ +package com.baeldung.string; + +public class ReplaceCharacterInString { + + public String replaceCharSubstring(String str, char ch, int index) { + String myString = str.substring(0, index) + ch + str.substring(index + 1); + return myString; + } + + public String replaceCharUsingCharArray(String str, char ch, int index) { + char[] chars = str.toCharArray(); + chars[index] = ch; + return String.valueOf(chars); + } + + + public String replaceCharStringBuilder(String str, char ch, int index) { + StringBuilder myString = new StringBuilder(str); + myString.setCharAt(index, ch); + return myString.toString(); + } + + public String replaceCharStringBuffer(String str, char ch, int index) { + StringBuffer myString = new StringBuffer(str); + myString.setCharAt(index, ch); + return myString.toString(); + } + +} diff --git a/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java b/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java new file mode 100644 index 0000000000..9462244bbb --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java @@ -0,0 +1,19 @@ +package com.baeldung.string.checkinputs; + +import java.util.Scanner; + +public class CheckIntegerInput { + + public static void main(String[] args) { + + try (Scanner scanner = new Scanner(System.in)) { + System.out.println("Enter an integer : "); + + if (scanner.hasNextInt()) { + System.out.println("You entered : " + scanner.nextInt()); + } else { + System.out.println("The input is not an integer"); + } + } + } +} \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java b/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java new file mode 100644 index 0000000000..c9d748e897 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java @@ -0,0 +1,103 @@ +package com.baeldung.string.removeleadingtrailingchar; + + +import org.apache.commons.lang3.StringUtils; + +import com.google.common.base.CharMatcher; + +public class RemoveLeadingAndTrailingZeroes { + + public static String removeLeadingZeroesWithStringBuilder(String s) { + StringBuilder sb = new StringBuilder(s); + + while (sb.length() > 1 && sb.charAt(0) == '0') { + sb.deleteCharAt(0); + } + + return sb.toString(); + } + + public static String removeTrailingZeroesWithStringBuilder(String s) { + StringBuilder sb = new StringBuilder(s); + + while (sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') { + sb.setLength(sb.length() - 1); + } + + return sb.toString(); + } + + public static String removeLeadingZeroesWithSubstring(String s) { + int index = 0; + + for (; index < s.length() - 1; index++) { + if (s.charAt(index) != '0') { + break; + } + } + + return s.substring(index); + } + + public static String removeTrailingZeroesWithSubstring(String s) { + int index = s.length() - 1; + + for (; index > 0; index--) { + if (s.charAt(index) != '0') { + break; + } + } + + return s.substring(0, index + 1); + } + + public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) { + String stripped = StringUtils.stripStart(s, "0"); + + if (stripped.isEmpty() && !s.isEmpty()) { + return "0"; + } + + return stripped; + } + + public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) { + String stripped = StringUtils.stripEnd(s, "0"); + + if (stripped.isEmpty() && !s.isEmpty()) { + return "0"; + } + + return stripped; + } + + public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) { + String stripped = CharMatcher.is('0') + .trimLeadingFrom(s); + + if (stripped.isEmpty() && !s.isEmpty()) { + return "0"; + } + + return stripped; + } + + public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) { + String stripped = CharMatcher.is('0') + .trimTrailingFrom(s); + + if (stripped.isEmpty() && !s.isEmpty()) { + return "0"; + } + + return stripped; + } + + public static String removeLeadingZeroesWithRegex(String s) { + return s.replaceAll("^0+(?!$)", ""); + } + + public static String removeTrailingZeroesWithRegex(String s) { + return s.replaceAll("(?!^)0+$", ""); + } +} diff --git a/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java index eeba81f334..d8fd9c4b14 100644 --- a/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java +++ b/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java @@ -44,16 +44,16 @@ public class RemoveDuplicateFromString { } String removeDuplicatesUsingSorting(String str) { - - char[] chars = str.toCharArray(); - - Arrays.sort(chars); - StringBuilder sb = new StringBuilder(); - sb.append(chars[0]); - for (int i = 1; i < chars.length; i++) { - if (chars[i] != chars[i - 1]) { - sb.append(chars[i]); + if(!str.isEmpty()) { + char[] chars = str.toCharArray(); + Arrays.sort(chars); + + sb.append(chars[0]); + for (int i = 1; i < chars.length; i++) { + if (chars[i] != chars[i - 1]) { + sb.append(chars[i]); + } } } @@ -90,6 +90,13 @@ public class RemoveDuplicateFromString { return sb.toString(); } + + String removeDuplicatesUsingDistinct(String str) { + StringBuilder sb = new StringBuilder(); + str.chars().distinct().forEach(c -> sb.append((char) c)); + return sb.toString(); + } + } diff --git a/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java b/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java new file mode 100644 index 0000000000..47357a99cc --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java @@ -0,0 +1,135 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.Function; +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; + +public class ConvertStringToListUnitTest { + + private final String countries = "Russia,Germany,England,France,Italy"; + private final String ranks = "1,2,3,4,5, 6,7"; + private final String emptyStrings = ",,,,,"; + private final List expectedCountriesList = Arrays.asList("Russia", "Germany", "England", "France", "Italy"); + private final List expectedRanksList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + private final List expectedEmptyStringsList = Arrays.asList("", "", "", "", "", ""); + + @Test + public void givenString_thenGetListOfStringByJava() { + List convertedCountriesList = Arrays.asList(countries.split(",", -1)); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByApache() { + List convertedCountriesList = Arrays.asList(StringUtils.splitPreserveAllTokens(countries, ",")); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByGuava() { + List convertedCountriesList = Splitter.on(",") + .trimResults() + .splitToList(countries); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByJava8() { + List convertedCountriesList = Stream.of(countries.split(",", -1)) + .collect(Collectors.toList()); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfIntegerByJava() { + String[] convertedRankArray = ranks.split(","); + List convertedRankList = new ArrayList(); + for (String number : convertedRankArray) { + convertedRankList.add(Integer.parseInt(number.trim())); + } + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByGuava() { + List convertedRankList = Lists.transform(Splitter.on(",") + .trimResults() + .splitToList(ranks), new Function() { + @Override + public Integer apply(String input) { + return Integer.parseInt(input.trim()); + } + }); + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByJava8() { + List convertedRankList = Stream.of(ranks.split(",")) + .map(String::trim) + .map(Integer::parseInt) + .collect(Collectors.toList()); + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByApache() { + String[] convertedRankArray = StringUtils.split(ranks, ","); + List convertedRankList = new ArrayList(); + for (String number : convertedRankArray) { + convertedRankList.add(Integer.parseInt(number.trim())); + } + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByJava() { + List convertedEmptyStringsList = Arrays.asList(emptyStrings.split(",", -1)); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByApache() { + List convertedEmptyStringsList = Arrays.asList(StringUtils.splitPreserveAllTokens(emptyStrings, ",")); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByGuava() { + List convertedEmptyStringsList = Splitter.on(",") + .trimResults() + .splitToList(emptyStrings); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByJava8() { + List convertedEmptyStringsList = Stream.of(emptyStrings.split(",", -1)) + .collect(Collectors.toList()); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java b/java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java new file mode 100644 index 0000000000..c25d4ce8f9 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.StringJoiner; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; + +public class StringConcatenationUnitTest { + + @Test + public void givenMultipleStrings_whenConcatUsingStringBuilder_checkStringCorrect() { + + StringBuilder stringBuilder = new StringBuilder(100); + stringBuilder.append("Baeldung"); + stringBuilder.append(" is"); + stringBuilder.append(" awesome"); + + assertEquals("Baeldung is awesome", stringBuilder.toString()); + + } + + @Test + public void givenMultipleString_whenConcatUsingAdditionOperator_checkStringCorrect() { + + String myString = "The " + "quick " + "brown " + "fox..."; + + assertEquals("The quick brown fox...", myString); + } + + + @Test + public void givenMultipleStrings_whenConcatUsingStringFormat_checkStringCorrect() { + + String myString = String.format("%s %s %.2f %s %s, %s...", "I", + "ate", + 2.5056302, + "blueberry", + "pies", + "oops"); + + + assertEquals("I ate 2.51 blueberry pies, oops...", myString); + } + + @Test + public void givenMultipleStrings_whenStringConcatUsed_checkStringCorrect() { + + String myString = "Both".concat(" fickle") + .concat(" dwarves") + .concat(" jinx") + .concat(" my") + .concat(" pig") + .concat(" quiz"); + + assertEquals("Both fickle dwarves jinx my pig quiz", myString); + + + } + + @Test + public void givenMultipleStrings_whenStringJoinUsed_checkStringCorrect() { + + String[] strings = {"I'm", "running", "out", "of", "pangrams!"}; + + String myString = String.join(" ", strings); + + assertEquals("I'm running out of pangrams!", myString); + + } + + @Test + public void givenMultipleStrings_whenStringJoinerUsed_checkStringCorrect() { + + StringJoiner fruitJoiner = new StringJoiner(", "); + fruitJoiner.add("Apples"); + fruitJoiner.add("Oranges"); + fruitJoiner.add("Bananas"); + + assertEquals("Apples, Oranges, Bananas", fruitJoiner.toString()); + } + + @Test + public void givenMultipleStrings_whenArrayJoiner_checkStringCorrect() { + + String[] myFavouriteLanguages = {"Java", "JavaScript", "Python"}; + + String toString = Arrays.toString(myFavouriteLanguages); + + assertEquals("[Java, JavaScript, Python]", toString); + } + + @Test + public void givenArrayListOfStrings_whenCollectorsJoin_checkStringCorrect() { + + List awesomeAnimals = Arrays.asList("Shark", "Panda", "Armadillo"); + + String animalString = awesomeAnimals.stream().collect(Collectors.joining(", ")); + + assertEquals("Shark, Panda, Armadillo", animalString); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java new file mode 100644 index 0000000000..c234c6953c --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ReplaceCharInStringUnitTest { + private ReplaceCharacterInString characterInString = new ReplaceCharacterInString(); + + @Test + public void whenReplaceCharAtIndexUsingSubstring_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharSubstring("abcde", 'm', 3)); + } + + @Test + public void whenReplaceCharAtIndexUsingCharArray_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharUsingCharArray("abcde", 'm', 3)); + } + + @Test + public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharStringBuilder("abcde", 'm', 3)); + } + + @Test + public void whenReplaceCharAtIndexUsingStringBuffer_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharStringBuffer("abcde", 'm', 3)); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java new file mode 100644 index 0000000000..c93089e543 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java @@ -0,0 +1,129 @@ +package com.baeldung.string; + +import com.google.common.base.Joiner; +import com.google.common.primitives.Chars; +import com.google.common.primitives.Ints; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import java.nio.CharBuffer; +import java.util.Arrays; +import java.util.StringJoiner; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class StringFromPrimitiveArrayUnitTest { + + private int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + + private char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; + + private char separatorChar = '-'; + + private String separator = String.valueOf(separatorChar); + + private String expectedIntString = "1-2-3-4-5-6-7-8-9"; + + private String expectedCharString = "a-b-c-d-e-f"; + + @Test + public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() { + assertThat(Arrays.stream(intArray) + .mapToObj(String::valueOf) + .collect(Collectors.joining(separator))) + .isEqualTo(expectedIntString); + } + + @Test + public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() { + assertThat(CharBuffer.wrap(charArray).chars() + .mapToObj(intChar -> String.valueOf((char) intChar)) + .collect(Collectors.joining(separator))) + .isEqualTo(expectedCharString); + } + + + @Test + public void giveIntArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() { + StringJoiner intStringJoiner = new StringJoiner(separator); + + Arrays.stream(intArray) + .mapToObj(String::valueOf) + .forEach(intStringJoiner::add); + + assertThat(intStringJoiner.toString()).isEqualTo(expectedIntString); + } + + @Test + public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() { + StringJoiner charStringJoiner = new StringJoiner(separator); + + CharBuffer.wrap(charArray).chars() + .mapToObj(intChar -> String.valueOf((char) intChar)) + .forEach(charStringJoiner::add); + + assertThat(charStringJoiner.toString()).isEqualTo(expectedCharString); + } + + @Test + public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() { + assertThat(StringUtils.join(intArray, separatorChar)).isEqualTo(expectedIntString); + assertThat(StringUtils.join(ArrayUtils.toObject(intArray), separator)).isEqualTo(expectedIntString); + } + + @Test + public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() { + assertThat(StringUtils.join(charArray, separatorChar)).isEqualTo(expectedCharString); + assertThat(StringUtils.join(ArrayUtils.toObject(charArray), separator)).isEqualTo(expectedCharString); + } + + @Test + public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() { + assertThat(Joiner.on(separator).join(Ints.asList(intArray))).isEqualTo(expectedIntString); + } + + @Test + public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() { + assertThat(Joiner.on(separator).join(Chars.asList(charArray))).isEqualTo(expectedCharString); + } + + @Test + public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() { + assertThat(joinIntArrayWithStringBuilder(intArray, separator)).isEqualTo(expectedIntString); + } + + @Test + public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() { + assertThat(joinCharArrayWithStringBuilder(charArray, separator)).isEqualTo(expectedCharString); + } + + private String joinIntArrayWithStringBuilder(int[] array, String separator) { + if (array.length == 0) { + return ""; + } + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < array.length - 1; i++) { + stringBuilder.append(array[i]); + stringBuilder.append(separator); + } + stringBuilder.append(array[array.length - 1]); + return stringBuilder.toString(); + } + + private String joinCharArrayWithStringBuilder(char[] array, String separator) { + if (array.length == 0) { + return ""; + } + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < array.length - 1; i++) { + stringBuilder.append(array[i]); + stringBuilder.append(separator); + } + stringBuilder.append(array[array.length - 1]); + return stringBuilder.toString(); + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java rename to java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java new file mode 100644 index 0000000000..a9f8a04c8d --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.string.conversion; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class ByteArrayToStringUnitTest { + + @Test + public void whenStringConstructorWithDefaultCharset_thenOK() { + final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33 }; + String string = new String(byteArrray); + System.out.println(string); + + assertNotNull(string); + } + + @Test + public void whenStringConstructorWithNamedCharset_thenOK() + throws UnsupportedEncodingException { + final String charsetName = "IBM01140"; + final byte[] byteArrray = { -56, -123, -109, -109, -106, 64, -26, -106, + -103, -109, -124, 90 }; + + String string = new String(byteArrray, charsetName); + + assertEquals("Hello World!", string); + } + + @Test + public void whenStringConstructorWithCharSet_thenOK() { + final Charset charset = Charset.forName("UTF-8"); + final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33 }; + + String string = new String(byteArrray, charset); + + assertEquals("Hello World!", string); + } + + @Test + public void whenStringConstructorWithStandardCharSet_thenOK() { + final Charset charset = StandardCharsets.UTF_16; + + final byte[] byteArrray = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, + 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }; + + String string = new String(byteArrray, charset); + + assertEquals("Hello World!", string); + } + + @Test + public void whenDecodeWithCharset_thenOK() { + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33 }; + final Charset charset = StandardCharsets.US_ASCII; + + String string = charset.decode(ByteBuffer.wrap(byteArrray)).toString(); + System.out.println(string); + + assertEquals("Hello �orl�!", string); + } + + @Test + public void whenUsingCharsetDecoder_thenOK() + throws CharacterCodingException { + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33}; + CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder(); + + decoder.onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .replaceWith("?"); + + String string = decoder.decode(ByteBuffer.wrap(byteArrray)).toString(); + + assertEquals("Hello ?orl?!", string); + } + + +} diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java new file mode 100644 index 0000000000..5377b4b28d --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java @@ -0,0 +1,122 @@ +package com.baeldung.string.conversion; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.UnsupportedEncodingException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import org.junit.Test; + +public class StringToByteArrayUnitTest { + + @Test + public void whenGetBytesWithDefaultCharset_thenOK() { + final String inputString = "Hello World!"; + final String defaultCharSet = Charset.defaultCharset() + .displayName(); + + byte[] byteArrray = inputString.getBytes(); + + System.out.printf( + "Using default charset:%s, Input String:%s, Output byte array:%s\n", + defaultCharSet, inputString, Arrays.toString(byteArrray)); + + assertNotNull(byteArrray); + assert (byteArrray.length >= inputString.length()); + } + + @Test + public void whenGetBytesWithNamedCharset_thenOK() + throws UnsupportedEncodingException { + final String inputString = "Hello World!"; + final String charsetName = "IBM01140"; + + byte[] byteArrray = inputString.getBytes("IBM01140"); + + System.out.printf( + "Using named charset:%s, Input String:%s, Output byte array:%s\n", + charsetName, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { -56, -123, -109, -109, -106, 64, -26, + -106, -103, -109, -124, 90 }, + byteArrray); + } + + @Test + public void whenGetBytesWithCharset_thenOK() { + final String inputString = "Hello ਸੰਸਾਰ!"; + final Charset charset = Charset.forName("ASCII"); + + byte[] byteArrray = inputString.getBytes(charset); + + System.out.printf( + "Using Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 }, + byteArrray); + } + + @Test + public void whenGetBytesWithStandardCharset_thenOK() { + final String inputString = "Hello World!"; + final Charset charset = StandardCharsets.UTF_16; + + byte[] byteArrray = inputString.getBytes(charset); + + System.out.printf( + "Using Standard Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, + 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }, + byteArrray); + } + + @Test + public void whenEncodeWithCharset_thenOK() { + final String inputString = "Hello ਸੰਸਾਰ!"; + final Charset charset = StandardCharsets.US_ASCII; + + byte[] byteArrray = charset.encode(inputString) + .array(); + + System.out.printf( + "Using encode with Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 }, + byteArrray); + } + + @Test + public void whenUsingCharsetEncoder_thenOK() + throws CharacterCodingException { + final String inputString = "Hello ਸੰਸਾਰ!"; + CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder(); + encoder.onMalformedInput(CodingErrorAction.IGNORE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .replaceWith(new byte[] { 0 }); + + byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString)) + .array(); + + System.out.printf( + "Using encode with CharsetEncoder:%s, Input String:%s, Output byte array:%s\n", + encoder, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 0, 0, 0, 0, 0, 33 }, + byteArrray); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java index f236c641c3..d760510c73 100644 --- a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java @@ -1,7 +1,6 @@ package com.baeldung.string.formatter; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -11,9 +10,11 @@ import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; +import java.util.Locale; import java.util.TimeZone; -import static org.junit.Assert.assertEquals; +import org.junit.BeforeClass; +import org.junit.Test; public class DateToStringFormatterUnitTest { @@ -40,7 +41,7 @@ public class DateToStringFormatterUnitTest { @Test public void whenDateConvertedUsingDateFormatToString_thenCorrect() { String formattedDate = DateFormat - .getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) + .getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US) .format(date); assertEquals(EXPECTED_STRING_DATE, formattedDate); diff --git a/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java b/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java new file mode 100644 index 0000000000..55f932fea1 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java @@ -0,0 +1,143 @@ +package com.baeldung.string.removeleadingtrailingchar; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class RemoveLeadingAndTrailingZeroesUnitTest { + + public static Stream leadingZeroTestProvider() { + return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("0abc", "abc"), Arguments.of("0123", "123"), Arguments.of("0000123", "123"), Arguments.of("1230", "1230"), Arguments.of("01230", "1230"), Arguments.of("01", "1"), + Arguments.of("0001", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "12034"), Arguments.of("1203400", "1203400")); + } + + public static Stream trailingZeroTestProvider() { + return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("abc0", "abc"), Arguments.of("1230", "123"), Arguments.of("1230000", "123"), Arguments.of("0123", "0123"), Arguments.of("01230", "0123"), Arguments.of("10", "1"), + Arguments.of("1000", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "0012034"), Arguments.of("1203400", "12034")); + } + + @ParameterizedTest + @MethodSource("leadingZeroTestProvider") + public void givenTestStrings_whenRemoveLeadingZeroesWithStringBuilder_thenReturnWithoutLeadingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithStringBuilder(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("trailingZeroTestProvider") + public void givenTestStrings_whenRemoveTrailingZeroesWithStringBuilder_thenReturnWithoutTrailingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithStringBuilder(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("leadingZeroTestProvider") + public void givenTestStrings_whenRemoveLeadingZeroesWithSubstring_thenReturnWithoutLeadingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithSubstring(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("trailingZeroTestProvider") + public void givenTestStrings_whenRemoveTrailingZeroesWithSubstring_thenReturnWithoutTrailingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithSubstring(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("leadingZeroTestProvider") + public void givenTestStrings_whenRemoveLeadingZeroesWithApacheCommonsStripStart_thenReturnWithoutLeadingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithApacheCommonsStripStart(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("trailingZeroTestProvider") + public void givenTestStrings_whenRemoveTrailingZeroesWithApacheCommonsStripEnd_thenReturnWithoutTrailingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithApacheCommonsStripEnd(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("leadingZeroTestProvider") + public void givenTestStrings_whenRemoveLeadingZeroesWithGuavaTrimLeadingFrom_thenReturnWithoutLeadingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithGuavaTrimLeadingFrom(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("trailingZeroTestProvider") + public void givenTestStrings_whenRemoveTrailingZeroesWithGuavaTrimTrailingFrom_thenReturnWithoutTrailingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithGuavaTrimTrailingFrom(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("leadingZeroTestProvider") + public void givenTestStrings_whenRemoveLeadingZeroesWithRegex_thenReturnWithoutLeadingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithRegex(input); + + // then + assertThat(result).isEqualTo(expected); + } + + @ParameterizedTest + @MethodSource("trailingZeroTestProvider") + public void givenTestStrings_whenRemoveTrailingZeroesWithRegex_thenReturnWithoutTrailingZeroes(String input, String expected) { + // given + + // when + String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithRegex(input); + + // then + assertThat(result).isEqualTo(expected); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java b/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java index cf7819ced3..895ecc4a3b 100644 --- a/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java @@ -8,6 +8,8 @@ public class RemoveDuplicateFromStringUnitTest { private final static String STR1 = "racecar"; private final static String STR2 = "J2ee programming"; + private final static String STR_EMPTY = ""; + private RemoveDuplicateFromString removeDuplicateFromString; @Before @@ -20,6 +22,8 @@ public class RemoveDuplicateFromStringUnitTest { public void whenUsingCharArray_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() { String str1 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR1); String str2 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR2); + String strEmpty = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR_EMPTY); + Assert.assertEquals("", strEmpty); Assert.assertEquals("ecar", str1); Assert.assertEquals("J2e poraming", str2); } @@ -28,6 +32,9 @@ public class RemoveDuplicateFromStringUnitTest { public void whenUsingLinkedHashSet_DuplicatesShouldBeRemovedAndItKeepStringOrder() { String str1 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR1); String str2 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR2); + + String strEmpty = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR_EMPTY); + Assert.assertEquals("", strEmpty); Assert.assertEquals("race", str1); Assert.assertEquals("J2e progamin", str2); } @@ -36,6 +43,9 @@ public class RemoveDuplicateFromStringUnitTest { public void whenUsingSorting_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() { String str1 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR1); String str2 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR2); + + String strEmpty = removeDuplicateFromString.removeDuplicatesUsingSorting(STR_EMPTY); + Assert.assertEquals("", strEmpty); Assert.assertEquals("acer", str1); Assert.assertEquals(" 2Jaegimnopr", str2); } @@ -44,6 +54,8 @@ public class RemoveDuplicateFromStringUnitTest { public void whenUsingHashSet_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() { String str1 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR1); String str2 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR2); + String strEmpty = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR_EMPTY); + Assert.assertEquals("", strEmpty); Assert.assertEquals("arce", str1); Assert.assertEquals(" pa2regiJmno", str2); } @@ -52,7 +64,19 @@ public class RemoveDuplicateFromStringUnitTest { public void whenUsingIndexOf_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() { String str1 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR1); String str2 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR2); + String strEmpty = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR_EMPTY); + Assert.assertEquals("", strEmpty); Assert.assertEquals("ecar", str1); Assert.assertEquals("J2e poraming", str2); } + + @Test + public void whenUsingJava8_DuplicatesShouldBeRemovedAndItKeepStringOrder() { + String str1 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR1); + String str2 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR2); + String strEmpty = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR_EMPTY); + Assert.assertEquals("", strEmpty); + Assert.assertEquals("race", str1); + Assert.assertEquals("J2e progamin", str2); + } } diff --git a/java-vavr-stream/pom.xml b/java-vavr-stream/pom.xml index 395d2c81ba..c92f3c8742 100644 --- a/java-vavr-stream/pom.xml +++ b/java-vavr-stream/pom.xml @@ -5,6 +5,7 @@ com.baeldung.samples java-vavr-stream 1.0 + java-vavr-stream jar diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml index e8ff8dfc36..7ba3ca61d0 100644 --- a/java-websocket/pom.xml +++ b/java-websocket/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung java-websocket - war 0.0.1-SNAPSHOT + java-websocket + war com.baeldung diff --git a/javafx/pom.xml b/javafx/pom.xml index c9c5bc294e..44e6f7e8da 100644 --- a/javafx/pom.xml +++ b/javafx/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 javafx - + javafx + parent-modules com.baeldung diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index 7b4eecd880..f00dd0ebe8 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -5,6 +5,7 @@ com.baeldung.javax-servlets javax-servlets 1.0-SNAPSHOT + javax-servlets war diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 22f1827213..5f2690b5b4 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung javaxval 0.1-SNAPSHOT - + javaxval + com.baeldung parent-modules diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 4f6e6a20fb..97ed2cc51d 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -1,430 +1,538 @@ - - 4.0.0 - jee-7 - 1.0-SNAPSHOT - war - JavaEE 7 Arquillian Archetype Sample + + 4.0.0 + jee-7 + 1.0-SNAPSHOT + jee-7 + war + JavaEE 7 Arquillian Archetype Sample - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - javax - javaee-api - ${javaee_api.version} - provided - + + + javax + javaee-api + ${javaee_api.version} + provided + - - org.jboss.arquillian.junit - arquillian-junit-container - test - - - org.jboss.arquillian.graphene - graphene-webdriver - ${graphene-webdriver.version} - pom - test - - - com.jayway.awaitility - awaitility - ${awaitility.version} - test - + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + org.jboss.arquillian.graphene + graphene-webdriver + ${graphene-webdriver.version} + pom + test + + + com.jayway.awaitility + awaitility + ${awaitility.version} + test + - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-impl-maven - test - jar - + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven + test + jar + - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-impl-maven-archive - test - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-io - commons-io - ${commons-io.version} - - - com.sun.faces - jsf-api - ${com.sun.faces.jsf.version} - - - com.sun.faces - jsf-impl - ${com.sun.faces.jsf.version} - - - javax.servlet - jstl - ${jstl.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp - jsp-api - ${jsp-api.version} - provided - - - taglibs - standard - ${taglibs.standard.version} - + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven-archive + test + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-io + commons-io + ${commons-io.version} + + + com.sun.faces + jsf-api + ${com.sun.faces.jsf.version} + + + com.sun.faces + jsf-impl + ${com.sun.faces.jsf.version} + + + javax.servlet + jstl + ${jstl.version} + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + javax.servlet.jsp + jsp-api + ${jsp-api.version} + provided + + + taglibs + standard + ${taglibs.standard.version} + - - javax.mvc - javax.mvc-api - 20160715 - - - org.glassfish.ozark - ozark - ${ozark.version} - + + javax.mvc + javax.mvc-api + 20160715 + + + org.glassfish.ozark + ozark + ${ozark.version} + - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - org.springframework.security - spring-security-taglibs - ${org.springframework.security.version} - - + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + + - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - false - - - - + + org.jboss.spec.javax.batch + jboss-batch-api_1.0_spec + 1.0.0.Final + + + org.jberet + jberet-core + 1.0.2.Final + + + org.jberet + jberet-support + 1.0.2.Final + + + org.jboss.spec.javax.transaction + jboss-transaction-api_1.2_spec + 1.0.0.Final + + + org.jboss.marshalling + jboss-marshalling + 1.4.2.Final + + + org.jboss.weld + weld-core + 2.1.1.Final + + + org.jboss.weld.se + weld-se + 2.1.1.Final + + + org.jberet + jberet-se + 1.0.2.Final + + + com.h2database + h2 + 1.4.178 + + + org.glassfish.jersey.containers + jersey-container-jetty-servlet + 2.22.1 + + - - - - org.jboss.arquillian - arquillian-bom - ${arquillian_core.version} - import - pom - - - org.jboss.arquillian.extension - arquillian-drone-bom - ${arquillian-drone-bom.version} - pom - import - - - + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-pmd-plugin + + + [3.8,) + + + check + + + + + + + + + + + + + - - - wildfly-managed-arquillian - - true - - - standalone-full.xml - ${project.build.directory}/wildfly-${version.wildfly} - - - - io.undertow - undertow-websockets-jsr - ${undertow-websockets-jsr.version} - test - - - org.jboss.resteasy - resteasy-client - ${resteasy.version} - test - - - org.jboss.resteasy - resteasy-jaxb-provider - ${resteasy.version} - test - - - org.jboss.resteasy - resteasy-json-p-provider - ${resteasy.version} - test - - - org.wildfly - wildfly-arquillian-container-managed - ${wildfly.version} - test - - + + + + org.jboss.arquillian + arquillian-bom + ${arquillian_core.version} + import + pom + + + org.jboss.arquillian.extension + arquillian-drone-bom + ${arquillian-drone-bom.version} + pom + import + + + - - - - - maven-dependency-plugin - ${maven-dependency-plugin.version} - - ${maven.test.skip} - - - - unpack - process-test-classes - - unpack - - - - - org.wildfly - wildfly-dist - ${wildfly.version} - zip - false - ${project.build.directory} - - - - - - - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - ${project.build.directory}/wildfly-${wildfly.version} - - - - - - - - - wildfly-remote-arquillian - - - io.undertow - undertow-websockets-jsr - ${undertow-websockets-jsr.version} - test - - - org.jboss.resteasy - resteasy-client - ${resteasy.version} - test - - - org.jboss.resteasy - resteasy-jaxb-provider - ${resteasy.version} - test - - - org.jboss.resteasy - resteasy-json-p-provider - ${resteasy.version} - test - - - org.wildfly - wildfly-arquillian-container-remote - ${wildfly.version} - test - - - - - glassfish-embedded-arquillian - - - org.glassfish.main.extras - glassfish-embedded-all - ${glassfish-embedded-all.version} - test - - - org.glassfish - javax.json - ${javax.json.version} - test - - - org.glassfish.tyrus - tyrus-client - ${tyrus.version} - test - - - org.glassfish.tyrus - tyrus-container-grizzly-client - ${tyrus.version} - test - - - org.glassfish.jersey.core - jersey-client - ${jersey.version} - test - - - org.jboss.arquillian.container - arquillian-glassfish-embedded-3.1 - ${arquillian-glassfish.version} - test - - - - - glassfish-remote-arquillian - - - org.glassfish - javax.json - ${javax.json.version} - test - - - org.glassfish.tyrus - tyrus-client - ${tyrus.version} - test - - - org.glassfish.tyrus - tyrus-container-grizzly-client - ${tyrus.version} - test - - - org.glassfish.jersey.core - jersey-client - ${jersey.version} - test - - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey.version} - test - - - org.glassfish.jersey.media - jersey-media-json-processing - ${jersey.version} - test - - - org.jboss.arquillian.container - arquillian-glassfish-remote-3.1 - ${arquillian-glassfish.version} - test - - - - - webdriver-chrome - - true - - - chrome - - - - webdriver-firefox - - firefox - - - + + + wildfly-managed-arquillian + + true + + + standalone-full.xml + ${project.build.directory}/wildfly-${version.wildfly} + + + + io.undertow + undertow-websockets-jsr + ${undertow-websockets-jsr.version} + test + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-json-p-provider + ${resteasy.version} + test + + + org.wildfly + wildfly-arquillian-container-managed + ${wildfly.version} + test + + + sun.jdk + jconsole + + + + - - - bintray-mvc-spec-maven - bintray - http://dl.bintray.com/mvc-spec/maven - - true - - - false - - - + + + + + maven-dependency-plugin + ${maven-dependency-plugin.version} + + ${maven.test.skip} + + + + unpack + process-test-classes + + unpack + + + + + org.wildfly + wildfly-dist + ${wildfly.version} + zip + false + ${project.build.directory} + + + sun.jdk + jconsole + + + + + + + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + ${project.build.directory}/wildfly-${wildfly.version} + + + + + + + + + wildfly-remote-arquillian + + + io.undertow + undertow-websockets-jsr + ${undertow-websockets-jsr.version} + test + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-json-p-provider + ${resteasy.version} + test + + + org.wildfly + wildfly-arquillian-container-remote + ${wildfly.version} + test + + + sun.jdk + jconsole + + + + + + + glassfish-embedded-arquillian + + + org.glassfish.main.extras + glassfish-embedded-all + ${glassfish-embedded-all.version} + test + + + org.glassfish + javax.json + ${javax.json.version} + test + + + org.glassfish.tyrus + tyrus-client + ${tyrus.version} + test + + + org.glassfish.tyrus + tyrus-container-grizzly-client + ${tyrus.version} + test + + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + test + + + org.jboss.arquillian.container + arquillian-glassfish-embedded-3.1 + ${arquillian-glassfish.version} + test + + + + + glassfish-remote-arquillian + + + org.glassfish + javax.json + ${javax.json.version} + test + + + org.glassfish.tyrus + tyrus-client + ${tyrus.version} + test + + + org.glassfish.tyrus + tyrus-container-grizzly-client + ${tyrus.version} + test + + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + test + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + test + + + org.glassfish.jersey.media + jersey-media-json-processing + ${jersey.version} + test + + + org.jboss.arquillian.container + arquillian-glassfish-remote-3.1 + ${arquillian-glassfish.version} + test + + + + + webdriver-chrome + + true + + + chrome + + + + webdriver-firefox + + firefox + + + - - 1.8 - 3.0.0 - 7.0 - 1.1.11.Final - 8.2.1.Final - 1.7.0 - 1.4.6.Final - 3.0.19.Final - 4.1.1 - 1.0.4 - 1.13 - 2.25 - 1.0.0.Final - 2.6 - 4.2.3.RELEASE - 2.21.0 - 1.1.2 - 2.4 - 2.2.14 - 4.5 - 2.0.1.Final - 3.1.0 - 2.1.0.Final - 2.8 - 1.2 - 2.2 - 20160715 - + + + bintray-mvc-spec-maven + bintray + http://dl.bintray.com/mvc-spec/maven + + true + + + false + + + - + + 1.8 + 3.0.0 + 7.0 + 1.1.11.Final + 8.2.1.Final + 1.7.0 + 1.4.6.Final + 3.0.19.Final + 4.1.1 + 1.0.4 + 1.13 + 2.25 + 1.0.0.Final + 2.6 + 4.2.3.RELEASE + 2.21.0 + 1.1.2 + 2.4 + 2.2.14 + 4.5 + 2.0.1.Final + 3.1.0 + 2.1.0.Final + 2.8 + 1.2 + 2.2 + 20160715 + + + \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/ChunkExceptionSkipReadListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/ChunkExceptionSkipReadListener.java new file mode 100644 index 0000000000..ce47de66af --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/ChunkExceptionSkipReadListener.java @@ -0,0 +1,11 @@ +package com.baeldung.batch.understanding; + +import javax.batch.api.chunk.listener.SkipReadListener; +import javax.inject.Named; + +@Named +public class ChunkExceptionSkipReadListener implements SkipReadListener { + @Override + public void onSkipReadItem(Exception e) throws Exception { + } +} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/CustomCheckPoint.java b/jee-7/src/main/java/com/baeldung/batch/understanding/CustomCheckPoint.java new file mode 100644 index 0000000000..ba4eeb9da8 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/CustomCheckPoint.java @@ -0,0 +1,22 @@ +package com.baeldung.batch.understanding; + +import javax.batch.api.chunk.AbstractCheckpointAlgorithm; +import javax.batch.runtime.context.JobContext; +import javax.inject.Inject; +import javax.inject.Named; + +@Named +public class CustomCheckPoint extends AbstractCheckpointAlgorithm { + + @Inject + JobContext jobContext; + + private Integer counterRead = 0; + + @Override + public boolean isReadyToCheckpoint() throws Exception { + counterRead = (Integer)jobContext.getTransientUserData(); + System.out.println("counterRead : " + counterRead); + return counterRead % 5 == 0; + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/DeciderJobSequence.java b/jee-7/src/main/java/com/baeldung/batch/understanding/DeciderJobSequence.java new file mode 100644 index 0000000000..6cc2012f23 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/DeciderJobSequence.java @@ -0,0 +1,14 @@ +package com.baeldung.batch.understanding; + +import javax.batch.api.Decider; +import javax.batch.runtime.StepExecution; +import javax.inject.Named; + +@Named +public class DeciderJobSequence implements Decider { + @Override + public String decide(StepExecution[] ses) throws Exception { + return "nothing"; + } + +} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/InjectSimpleBatchLet.java b/jee-7/src/main/java/com/baeldung/batch/understanding/InjectSimpleBatchLet.java new file mode 100644 index 0000000000..ccc052b44b --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/InjectSimpleBatchLet.java @@ -0,0 +1,38 @@ +package com.baeldung.batch.understanding; + +import java.util.Properties; +import java.util.logging.Logger; + +import javax.batch.api.AbstractBatchlet; +import javax.batch.api.BatchProperty; +import javax.batch.runtime.BatchStatus; +import javax.batch.runtime.context.JobContext; +import javax.batch.runtime.context.StepContext; +import javax.inject.Inject; +import javax.inject.Named; + +@Named +public class InjectSimpleBatchLet extends AbstractBatchlet { + Logger logger = Logger.getLogger(InjectSimpleBatchLet.class.getName()); + + @Inject + @BatchProperty(name = "name") + private String nameString; + + @Inject + StepContext stepContext; + private Properties stepProperties; + @Inject + JobContext jobContext; + private Properties jobProperties; + + @Override + public String process() throws Exception { + logger.info("BatchProperty : " + nameString); + stepProperties = stepContext.getProperties(); + jobProperties = jobContext.getProperties(); + logger.info("Step property : "+ stepProperties.getProperty("stepProp1")); + logger.info("job property : "+jobProperties.getProperty("jobProp1")); + return BatchStatus.COMPLETED.toString(); + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleBatchLet.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleBatchLet.java new file mode 100644 index 0000000000..6a367b064b --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleBatchLet.java @@ -0,0 +1,13 @@ +package com.baeldung.batch.understanding; + +import javax.batch.api.AbstractBatchlet; +import javax.batch.runtime.BatchStatus; +import javax.inject.Named; + +@Named +public class SimpleBatchLet extends AbstractBatchlet { + @Override + public String process() throws Exception { + return BatchStatus.FAILED.toString(); + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemProcessor.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemProcessor.java new file mode 100644 index 0000000000..3f8166b6d8 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemProcessor.java @@ -0,0 +1,12 @@ +package com.baeldung.batch.understanding; + +import javax.batch.api.chunk.ItemProcessor; +import javax.inject.Named; + +@Named +public class SimpleChunkItemProcessor implements ItemProcessor { + @Override + public Integer processItem(Object t) { + return ((Integer) t).intValue() % 2 == 0 ? null : ((Integer) t).intValue(); + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReader.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReader.java new file mode 100644 index 0000000000..7d66edc74c --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReader.java @@ -0,0 +1,36 @@ +package com.baeldung.batch.understanding; + +import java.io.Serializable; +import java.util.Properties; +import java.util.StringTokenizer; +import javax.batch.api.chunk.AbstractItemReader; +import javax.batch.runtime.BatchStatus; +import javax.batch.runtime.context.JobContext; +import javax.inject.Inject; +import javax.inject.Named; + +@Named +public class SimpleChunkItemReader extends AbstractItemReader { + private StringTokenizer tokens; + private Integer count=0; + + @Inject + JobContext jobContext; + + @Override + public Integer readItem() throws Exception { + if (tokens.hasMoreTokens()) { + this.count++; + String tempTokenize = tokens.nextToken(); + jobContext.setTransientUserData(count); + return Integer.valueOf(tempTokenize); + } + return null; + } + + @Override + public void open(Serializable checkpoint) throws Exception { + tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ","); + } + +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReaderError.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReaderError.java new file mode 100644 index 0000000000..f51426339f --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReaderError.java @@ -0,0 +1,36 @@ +package com.baeldung.batch.understanding; + +import java.io.Serializable; +import java.util.StringTokenizer; + +import javax.batch.api.chunk.AbstractItemReader; +import javax.batch.runtime.context.JobContext; +import javax.inject.Inject; +import javax.inject.Named; + +@Named +public class SimpleChunkItemReaderError extends AbstractItemReader { + @Inject + JobContext jobContext; + private StringTokenizer tokens; + private Integer count = 0; + + @Override + public Integer readItem() throws Exception { + if (tokens.hasMoreTokens()) { + count++; + jobContext.setTransientUserData(count); + int token = Integer.valueOf(tokens.nextToken()); + if (token == 3) { + throw new RuntimeException("Something happened"); + } + return Integer.valueOf(token); + } + return null; + } + + @Override + public void open(Serializable checkpoint) throws Exception { + tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ","); + } +} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkWriter.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkWriter.java new file mode 100644 index 0000000000..f21dd77b85 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkWriter.java @@ -0,0 +1,16 @@ +package com.baeldung.batch.understanding; + +import java.util.ArrayList; +import java.util.List; + +import javax.batch.api.chunk.AbstractItemWriter; +import javax.inject.Named; + +@Named +public class SimpleChunkWriter extends AbstractItemWriter { + List processed = new ArrayList<>(); + @Override + public void writeItems(List items) throws Exception { + items.stream().map(Integer.class::cast).forEach(this.processed::add); + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyInputRecord.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyInputRecord.java new file mode 100644 index 0000000000..e813a699c2 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyInputRecord.java @@ -0,0 +1,41 @@ +package com.baeldung.batch.understanding.exception; + +import java.io.Serializable; + +public class MyInputRecord implements Serializable { + private int id; + + public MyInputRecord(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + MyInputRecord that = (MyInputRecord) o; + + return id == that.id; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public String toString() { + return "MyInputRecord: " + id; + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemProcessor.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemProcessor.java new file mode 100644 index 0000000000..4427a1f548 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemProcessor.java @@ -0,0 +1,15 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.ItemProcessor; +import javax.inject.Named; + +@Named +public class MyItemProcessor implements ItemProcessor { + @Override + public Object processItem(Object t) { + if (((MyInputRecord) t).getId() == 6) { + throw new NullPointerException(); + } + return new MyOutputRecord(((MyInputRecord) t).getId()); + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemReader.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemReader.java new file mode 100644 index 0000000000..dd1876ab7d --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemReader.java @@ -0,0 +1,42 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.AbstractItemReader; +import javax.inject.Named; +import java.io.Serializable; +import java.util.StringTokenizer; + +@Named +public class MyItemReader extends AbstractItemReader { + private StringTokenizer tokens; + private MyInputRecord lastElement; + private boolean alreadyFailed; + + @Override + public void open(Serializable checkpoint) { + tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ","); + if (checkpoint != null) { + while (!Integer.valueOf(tokens.nextToken()) + .equals(((MyInputRecord) checkpoint).getId())) { + } + } + } + + @Override + public Object readItem() { + if (tokens.hasMoreTokens()) { + int token = Integer.valueOf(tokens.nextToken()); + if (token == 5 && !alreadyFailed) { + alreadyFailed = true; + throw new IllegalArgumentException("Could not read record"); + } + lastElement = new MyInputRecord(token); + return lastElement; + } + return null; + } + + @Override + public Serializable checkpointInfo() throws Exception { + return lastElement; + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemWriter.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemWriter.java new file mode 100644 index 0000000000..4e80d86d44 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemWriter.java @@ -0,0 +1,19 @@ + +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.AbstractItemWriter; +import javax.inject.Named; +import java.util.List; + +@Named +public class MyItemWriter extends AbstractItemWriter { + private static int retries = 0; + + @Override + public void writeItems(List list) { + if (retries <= 3 && list.contains(new MyOutputRecord(8))) { + retries++; + throw new UnsupportedOperationException(); + } + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyOutputRecord.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyOutputRecord.java new file mode 100644 index 0000000000..8f18fca7ba --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyOutputRecord.java @@ -0,0 +1,39 @@ +package com.baeldung.batch.understanding.exception; + +import java.io.Serializable; + +public class MyOutputRecord implements Serializable { + private int id; + + public MyOutputRecord(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + MyOutputRecord that = (MyOutputRecord) o; + + return id == that.id; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public String toString() { + return "MyOutputRecord: " + id; + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryProcessorListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryProcessorListener.java new file mode 100644 index 0000000000..3bd35820c3 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryProcessorListener.java @@ -0,0 +1,11 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.listener.RetryProcessListener; +import javax.inject.Named; + +@Named +public class MyRetryProcessorListener implements RetryProcessListener { + @Override + public void onRetryProcessException(Object item, Exception ex) throws Exception { + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryReadListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryReadListener.java new file mode 100644 index 0000000000..5c4f56b75d --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryReadListener.java @@ -0,0 +1,11 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.listener.RetryReadListener; +import javax.inject.Named; + +@Named +public class MyRetryReadListener implements RetryReadListener { + @Override + public void onRetryReadException(Exception ex) throws Exception { + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryWriteListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryWriteListener.java new file mode 100644 index 0000000000..a8683d86a9 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryWriteListener.java @@ -0,0 +1,12 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.listener.RetryWriteListener; +import javax.inject.Named; +import java.util.List; + +@Named +public class MyRetryWriteListener implements RetryWriteListener { + @Override + public void onRetryWriteException(List items, Exception ex) throws Exception { + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipProcessorListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipProcessorListener.java new file mode 100644 index 0000000000..74f7565cf7 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipProcessorListener.java @@ -0,0 +1,11 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.listener.SkipProcessListener; +import javax.inject.Named; + +@Named +public class MySkipProcessorListener implements SkipProcessListener { + @Override + public void onSkipProcessItem(Object t, Exception e) throws Exception { + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipReadListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipReadListener.java new file mode 100644 index 0000000000..aecaf93e75 --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipReadListener.java @@ -0,0 +1,11 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.listener.SkipReadListener; +import javax.inject.Named; + +@Named +public class MySkipReadListener implements SkipReadListener { + @Override + public void onSkipReadItem(Exception e) throws Exception { + } +} diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipWriteListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipWriteListener.java new file mode 100644 index 0000000000..928773b61d --- /dev/null +++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipWriteListener.java @@ -0,0 +1,13 @@ +package com.baeldung.batch.understanding.exception; + +import javax.batch.api.chunk.listener.SkipWriteListener; +import javax.inject.Named; +import java.util.List; + +@Named +public class MySkipWriteListener implements SkipWriteListener { + @Override + public void onSkipWriteItem(List list, Exception e) throws Exception { + list.remove(new MyOutputRecord(2)); + } +} diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/customCheckPoint.xml b/jee-7/src/main/resources/META-INF/batch-jobs/customCheckPoint.xml new file mode 100644 index 0000000000..b0f327dd39 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/customCheckPoint.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/decideJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/decideJobSequence.xml new file mode 100644 index 0000000000..4905586fb9 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/decideJobSequence.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/flowJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/flowJobSequence.xml new file mode 100644 index 0000000000..207a9242b1 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/flowJobSequence.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/injectionSimpleBatchLet.xml b/jee-7/src/main/resources/META-INF/batch-jobs/injectionSimpleBatchLet.xml new file mode 100644 index 0000000000..39cb043dcf --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/injectionSimpleBatchLet.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/partitionSimpleBatchLet.xml b/jee-7/src/main/resources/META-INF/batch-jobs/partitionSimpleBatchLet.xml new file mode 100644 index 0000000000..49495072ea --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/partitionSimpleBatchLet.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleBatchLet.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleBatchLet.xml new file mode 100644 index 0000000000..9c707de8a4 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleBatchLet.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleChunk.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleChunk.xml new file mode 100644 index 0000000000..b2b15b7bd9 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleChunk.xml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorChunk.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorChunk.xml new file mode 100644 index 0000000000..743fcafd65 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorChunk.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorSkipChunk.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorSkipChunk.xml new file mode 100644 index 0000000000..2fafb83cc7 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorSkipChunk.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleJobSequence.xml new file mode 100644 index 0000000000..7110db7f23 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleJobSequence.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/splitJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/splitJobSequence.xml new file mode 100644 index 0000000000..0a9ea97dc7 --- /dev/null +++ b/jee-7/src/main/resources/META-INF/batch-jobs/splitJobSequence.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7/src/main/resources/META-INF/beans.xml b/jee-7/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..ae0f4bf2ee --- /dev/null +++ b/jee-7/src/main/resources/META-INF/beans.xml @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/BatchTestHelper.java b/jee-7/src/test/java/com/baeldung/batch/understanding/BatchTestHelper.java new file mode 100644 index 0000000000..56269809f3 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/BatchTestHelper.java @@ -0,0 +1,90 @@ +package com.baeldung.batch.understanding; + +import java.util.HashMap; +import java.util.Map; + +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; + +public class BatchTestHelper { + private static final int MAX_TRIES = 40; + private static final int THREAD_SLEEP = 1000; + + private BatchTestHelper() { + throw new UnsupportedOperationException(); + } + + public static JobExecution keepTestAlive(JobExecution jobExecution) throws InterruptedException { + int maxTries = 0; + while (!jobExecution.getBatchStatus() + .equals(BatchStatus.COMPLETED)) { + if (maxTries < MAX_TRIES) { + maxTries++; + Thread.sleep(THREAD_SLEEP); + jobExecution = BatchRuntime.getJobOperator() + .getJobExecution(jobExecution.getExecutionId()); + } else { + break; + } + } + Thread.sleep(THREAD_SLEEP); + return jobExecution; + } + + public static JobExecution keepTestFailed(JobExecution jobExecution) throws InterruptedException { + int maxTries = 0; + while (!jobExecution.getBatchStatus() + .equals(BatchStatus.FAILED)) { + if (maxTries < MAX_TRIES) { + maxTries++; + Thread.sleep(THREAD_SLEEP); + jobExecution = BatchRuntime.getJobOperator() + .getJobExecution(jobExecution.getExecutionId()); + } else { + break; + } + } + Thread.sleep(THREAD_SLEEP); + + return jobExecution; + } + + public static JobExecution keepTestStopped(JobExecution jobExecution) throws InterruptedException { + int maxTries = 0; + while (!jobExecution.getBatchStatus() + .equals(BatchStatus.STOPPED)) { + if (maxTries < MAX_TRIES) { + maxTries++; + Thread.sleep(THREAD_SLEEP); + jobExecution = BatchRuntime.getJobOperator() + .getJobExecution(jobExecution.getExecutionId()); + } else { + break; + } + } + Thread.sleep(THREAD_SLEEP); + return jobExecution; + } + + public static long getCommitCount(StepExecution stepExecution) { + Map metricsMap = getMetricsMap(stepExecution.getMetrics()); + return metricsMap.get(Metric.MetricType.COMMIT_COUNT); + } + + public static long getProcessSkipCount(StepExecution stepExecution) { + Map metricsMap = getMetricsMap(stepExecution.getMetrics()); + return metricsMap.get(Metric.MetricType.PROCESS_SKIP_COUNT); + } + + public static Map getMetricsMap(Metric[] metrics) { + Map metricsMap = new HashMap<>(); + for (Metric metric : metrics) { + metricsMap.put(metric.getType(), metric.getValue()); + } + return metricsMap; + } + +} 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 new file mode 100644 index 0000000000..dfea878a75 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.batch.understanding; + +import static org.junit.jupiter.api.Assertions.*; +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; +import javax.batch.runtime.StepExecution; +import com.baeldung.batch.understanding.BatchTestHelper; + +import org.junit.jupiter.api.Test; + +class CustomCheckPointUnitTest { + @Test + public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("customCheckPoint", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + for (StepExecution stepExecution : jobOperator.getStepExecutions(executionId)) { + if (stepExecution.getStepName() + .equals("firstChunkStep")) { + jobOperator.getStepExecutions(executionId) + .stream() + .map(BatchTestHelper::getCommitCount) + .forEach(count -> assertEquals(3L, count.longValue())); + } + } + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } +} 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 new file mode 100644 index 0000000000..7c5e8d0b78 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.batch.understanding; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.ArrayList; +import java.util.List; +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.StepExecution; + +import org.junit.jupiter.api.Test; + +class JobSequenceUnitTest { + @Test + public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleJobSequence", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + assertEquals(2 , jobOperator.getStepExecutions(executionId).size()); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + @Test + public void givenFlow_thenBatch_CompleteWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("flowJobSequence", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + assertEquals(3 , jobOperator.getStepExecutions(executionId).size()); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + @Test + public void givenDecider_thenBatch_CompleteWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("decideJobSequence", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + List stepExecutions = jobOperator.getStepExecutions(executionId); + List executedSteps = new ArrayList<>(); + for (StepExecution stepExecution : stepExecutions) { + executedSteps.add(stepExecution.getStepName()); + } + assertEquals(2, jobOperator.getStepExecutions(executionId).size()); + assertArrayEquals(new String[] { "firstBatchStepStep1", "firstBatchStepStep3" }, executedSteps.toArray()); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + @Test + public void givenSplit_thenBatch_CompletesWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("splitJobSequence", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + List stepExecutions = jobOperator.getStepExecutions(executionId); + List executedSteps = new ArrayList<>(); + for (StepExecution stepExecution : stepExecutions) { + executedSteps.add(stepExecution.getStepName()); + } + assertEquals(3, stepExecutions.size()); + assertTrue(executedSteps.contains("splitJobSequenceStep1")); + assertTrue(executedSteps.contains("splitJobSequenceStep2")); + assertTrue(executedSteps.contains("splitJobSequenceStep3")); + assertTrue(executedSteps.get(0).equals("splitJobSequenceStep1") || executedSteps.get(0).equals("splitJobSequenceStep2")); + assertTrue(executedSteps.get(1).equals("splitJobSequenceStep1") || executedSteps.get(1).equals("splitJobSequenceStep2")); + assertTrue(executedSteps.get(2).equals("splitJobSequenceStep3")); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } +} 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 new file mode 100644 index 0000000000..ade492b1b9 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.batch.understanding; + +import static org.junit.jupiter.api.Assertions.*; +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 { + @Test + public void givenBatchLet_thenBatch_CompleteWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleBatchLet", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + @Test + public void givenBatchLetProperty_thenBatch_CompleteWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("injectionSimpleBatchLet", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + @Test + public void givenBatchLetPartition_thenBatch_CompleteWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("partitionSimpleBatchLet", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + @Test + public void givenBatchLetStarted_whenStopped_thenBatchStopped() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleBatchLet", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobOperator.stop(executionId); + jobExecution = BatchTestHelper.keepTestStopped(jobExecution); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.STOPPED); + } + + @Test + public void givenBatchLetStopped_whenRestarted_thenBatchCompletesSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleBatchLet", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobOperator.stop(executionId); + jobExecution = BatchTestHelper.keepTestStopped(jobExecution); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.STOPPED); + executionId = jobOperator.restart(jobExecution.getExecutionId(), new Properties()); + jobExecution = BatchTestHelper.keepTestAlive(jobOperator.getJobExecution(executionId)); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } +} 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 new file mode 100644 index 0000000000..57c794ba00 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.batch.understanding; + +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; +import javax.batch.runtime.StepExecution; + +import org.junit.jupiter.api.Test; + +class SimpleChunkUnitTest { + @Test + public void givenChunk_thenBatch_CompletesWithSucess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleChunk", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + List stepExecutions = jobOperator.getStepExecutions(executionId); + for (StepExecution stepExecution : stepExecutions) { + if (stepExecution.getStepName() + .equals("firstChunkStep")) { + Map metricsMap = BatchTestHelper.getMetricsMap(stepExecution.getMetrics()); + assertEquals(10L, metricsMap.get(Metric.MetricType.READ_COUNT) + .longValue()); + assertEquals(10L / 2L, metricsMap.get(Metric.MetricType.WRITE_COUNT) + .longValue()); + assertEquals(10L / 3 + (10L % 3 > 0 ? 1 : 0), metricsMap.get(Metric.MetricType.COMMIT_COUNT) + .longValue()); + } + } + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } + + @Test + public void givenChunk__thenBatch_fetchInformation() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleChunk", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + // job name contains simpleBatchLet which is the name of the file + assertTrue(jobOperator.getJobNames().contains("simpleChunk")); + // job parameters are empty + assertTrue(jobOperator.getParameters(executionId).isEmpty()); + // step execution information + List stepExecutions = jobOperator.getStepExecutions(executionId); + assertEquals("firstChunkStep", stepExecutions.get(0).getStepName()); + // finding out batch status + assertEquals(BatchStatus.COMPLETED, stepExecutions.get(0).getBatchStatus()); + Map metricTest = BatchTestHelper.getMetricsMap(stepExecutions.get(0).getMetrics()); + assertEquals(10L, metricTest.get(Metric.MetricType.READ_COUNT).longValue()); + assertEquals(5L, metricTest.get(Metric.MetricType.FILTER_COUNT).longValue()); + assertEquals(4L, metricTest.get(Metric.MetricType.COMMIT_COUNT).longValue()); + assertEquals(5L, metricTest.get(Metric.MetricType.WRITE_COUNT).longValue()); + assertEquals(0L, metricTest.get(Metric.MetricType.READ_SKIP_COUNT).longValue()); + assertEquals(0L, metricTest.get(Metric.MetricType.WRITE_SKIP_COUNT).longValue()); + assertEquals(0L, metricTest.get(Metric.MetricType.PROCESS_SKIP_COUNT).longValue()); + assertEquals(0L, metricTest.get(Metric.MetricType.ROLLBACK_COUNT).longValue()); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } +} 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 new file mode 100644 index 0000000000..ded31b6345 --- /dev/null +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java @@ -0,0 +1,48 @@ +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; + +class SimpleErrorChunkUnitTest { + + @Test + public void givenChunkError_thenBatch_CompletesWithFailed() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleErrorChunk", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestFailed(jobExecution); + assertEquals(jobExecution.getBatchStatus(), BatchStatus.FAILED); + } + + @Test + public void givenChunkError_thenErrorSkipped_CompletesWithSuccess() throws Exception { + JobOperator jobOperator = BatchRuntime.getJobOperator(); + Long executionId = jobOperator.start("simpleErrorSkipChunk", new Properties()); + JobExecution jobExecution = jobOperator.getJobExecution(executionId); + jobExecution = BatchTestHelper.keepTestAlive(jobExecution); + List stepExecutions = jobOperator.getStepExecutions(executionId); + for (StepExecution stepExecution : stepExecutions) { + if (stepExecution.getStepName() + .equals("errorStep")) { + jobOperator.getStepExecutions(executionId) + .stream() + .map(BatchTestHelper::getProcessSkipCount) + .forEach(skipCount -> assertEquals(1L, skipCount.longValue())); + } + } + assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED); + } +} diff --git a/jenkins/hello-world/pom.xml b/jenkins/hello-world/pom.xml index fb2154c7ad..f00a551173 100644 --- a/jenkins/hello-world/pom.xml +++ b/jenkins/hello-world/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - jenkins-hello-world + hello-world 1.0-SNAPSHOT + hello-world hpi - Hello World Plugin A sample Jenkins Hello World plugin diff --git a/jersey/pom.xml b/jersey/pom.xml index b55bdc5330..a3adb4cf5a 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - com.baeldung jersey 0.0.1-SNAPSHOT + jersey war diff --git a/jhipster/README.md b/jhipster/README.md index f3655f8ec1..91ba54bf60 100644 --- a/jhipster/README.md +++ b/jhipster/README.md @@ -2,3 +2,4 @@ - [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices) - [Intro to JHipster](http://www.baeldung.com/jhipster) +- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) diff --git a/jhipster/jhipster-microservice/pom.xml b/jhipster/jhipster-microservice/pom.xml index 4a60e47f87..051d5f70b7 100644 --- a/jhipster/jhipster-microservice/pom.xml +++ b/jhipster/jhipster-microservice/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 jhipster-microservice + jhipster-microservice pom - JHipster Microservice - + jhipster com.baeldung.jhipster diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index d321e9e81e..a2c267b74d 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,7 +1,5 @@ ### Relevant articles -- [Intro to JHipster](http://www.baeldung.com/jhipster) - # baeldung This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8). diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index e242668759..12dead99df 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -3,6 +3,7 @@ 4.0.0 jhipster-monolithic war + jhipster-monolithic JHipster Monolithic Application diff --git a/jhipster/jhipster-uaa/pom.xml b/jhipster/jhipster-uaa/pom.xml new file mode 100644 index 0000000000..e8ccaabfb0 --- /dev/null +++ b/jhipster/jhipster-uaa/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + com.baeldung.jhipster + jhipster-microservice-uaa + pom + JHipster Microservice with UAA + + + jhipster + com.baeldung.jhipster + 1.0.0-SNAPSHOT + + + + uaa + gateway + quotes + + + diff --git a/jhipster/pom.xml b/jhipster/pom.xml index 2bf7bcb233..5132c6dc95 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -18,6 +18,7 @@ jhipster-monolithic jhipster-microservice + jhipster-uaa diff --git a/jib/pom.xml b/jib/pom.xml index e71250f157..ad4011c3c4 100644 --- a/jib/pom.xml +++ b/jib/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jib 0.1-SNAPSHOT @@ -42,16 +42,4 @@ - - - spring-releases - https://repo.spring.io/libs-release - - - - - spring-releases - https://repo.spring.io/libs-release - - diff --git a/jni/pom.xml b/jni/pom.xml index d4cc409d33..4850e07ed7 100644 --- a/jni/pom.xml +++ b/jni/pom.xml @@ -2,7 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jni - + jni + com.baeldung parent-modules diff --git a/jsf/pom.xml b/jsf/pom.xml index 2ac8a9f7c2..fc6d4a0ee2 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -4,6 +4,7 @@ 4.0.0 jsf 0.1-SNAPSHOT + jsf war diff --git a/json/pom.xml b/json/pom.xml index b688baec06..fce2d26db5 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -4,7 +4,8 @@ org.baeldung json 0.0.1-SNAPSHOT - + json + com.baeldung parent-modules @@ -32,6 +33,16 @@ org.json json 20171018 + + + com.google.code.gson + gson + 2.8.5 + + + com.fasterxml.jackson.core + jackson-databind + 2.9.7 javax.json.bind diff --git a/json/src/main/java/com/baeldung/escape/JsonEscape.java b/json/src/main/java/com/baeldung/escape/JsonEscape.java new file mode 100644 index 0000000000..1e5f0d87cb --- /dev/null +++ b/json/src/main/java/com/baeldung/escape/JsonEscape.java @@ -0,0 +1,41 @@ +package com.baeldung.escape; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonObject; +import org.json.JSONObject; + +class JsonEscape { + + String escapeJson(String input) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("message", input); + return jsonObject.toString(); + } + + String escapeGson(String input) { + JsonObject gsonObject = new JsonObject(); + gsonObject.addProperty("message", input); + return gsonObject.toString(); + } + + String escapeJackson(String input) throws JsonProcessingException { + return new ObjectMapper().writeValueAsString(new Payload(input)); + } + + static class Payload { + String message; + + Payload(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } +} diff --git a/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java new file mode 100644 index 0000000000..e959fa227b --- /dev/null +++ b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.escape; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class JsonEscapeUnitTest { + + private JsonEscape testedInstance; + private static final String EXPECTED = "{\"message\":\"Hello \\\"World\\\"\"}"; + + @BeforeEach + void setUp() { + testedInstance = new JsonEscape(); + } + + @Test + void escapeJson() { + String actual = testedInstance.escapeJson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } + + @Test + void escapeGson() { + String actual = testedInstance.escapeGson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } + + @Test + void escapeJackson() throws JsonProcessingException { + String actual = testedInstance.escapeJackson("Hello \"World\""); + assertEquals(EXPECTED, actual); + } +} \ No newline at end of file diff --git a/jsoup/pom.xml b/jsoup/pom.xml index 2704d7bc00..f6e25e7a23 100644 --- a/jsoup/pom.xml +++ b/jsoup/pom.xml @@ -3,6 +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 jsoup + jsoup jar diff --git a/jta/pom.xml b/jta/pom.xml index 89bdccf25e..4754c1872b 100644 --- a/jta/pom.xml +++ b/jta/pom.xml @@ -3,8 +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 - jta-demo + jta 1.0-SNAPSHOT + jta jar JEE JTA demo diff --git a/jws/pom.xml b/jws/pom.xml index 1970ab9921..2c89b687f8 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -3,9 +3,9 @@ 4.0.0 com.example jws - war 0.0.1-SNAPSHOT - jws-example + jws + war com.baeldung diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md index b9611043c8..4110bfe12e 100644 --- a/kotlin-libraries/README.md +++ b/kotlin-libraries/README.md @@ -5,6 +5,7 @@ - [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection) - [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek) - [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson) -- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor) - [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) diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index 92a643e458..ae77a9aa2d 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -3,6 +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 kotlin-libraries + kotlin-libraries jar diff --git a/libraries-apache-commons/.gitignore b/libraries-apache-commons/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-apache-commons/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-apache-commons/README.md b/libraries-apache-commons/README.md new file mode 100644 index 0000000000..01f2379588 --- /dev/null +++ b/libraries-apache-commons/README.md @@ -0,0 +1,20 @@ +### Relevant articles + +- [Array Processing with Apache Commons Lang 3](http://www.baeldung.com/array-processing-commons-lang) +- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) +- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) +- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) +- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) +- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) +- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) +- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) +- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) +- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) +- [Apache Commons IO](http://www.baeldung.com/apache-commons-io) +- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) +- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) +- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils) +- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map) +- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) +- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) +- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) \ No newline at end of file diff --git a/libraries-apache-commons/log4j.properties b/libraries-apache-commons/log4j.properties new file mode 100644 index 0000000000..2173c5d96f --- /dev/null +++ b/libraries-apache-commons/log4j.properties @@ -0,0 +1 @@ +log4j.rootLogger=INFO, stdout diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml new file mode 100644 index 0000000000..c7ff918af9 --- /dev/null +++ b/libraries-apache-commons/pom.xml @@ -0,0 +1,109 @@ + + + 4.0.0 + libraries-apache-commons + libraries-apache-commons + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + commons-io + commons-io + ${commons.io.version} + + + commons-chain + commons-chain + ${commons-chain.version} + + + org.apache.commons + commons-csv + ${commons-csv.version} + + + commons-dbutils + commons-dbutils + ${commons.dbutils.version} + + + org.apache.commons + commons-math3 + ${common-math3.version} + + + commons-net + commons-net + ${commons-net.version} + + + com.h2database + h2 + ${h2.version} + + + org.knowm.xchart + xchart + ${xchart-version} + + + org.apache.commons + commons-collections4 + ${commons.collections.version} + + + org.hamcrest + java-hamcrest + ${org.hamcrest.java-hamcrest.version} + test + + + + + + 3.6 + 1.1 + 1.9.3 + 1.2 + 1.4 + 3.6.2 + 2.5 + 1.6 + 1.4.196 + 4.1 + 4.12 + 2.0.0.0 + 1.10.L001 + 3.5.2 + 3.6 + 1.3 + 3.6.1 + + + diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/Course.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Course.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/Course.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Course.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseService.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseService.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/Student.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Student.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/Student.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Student.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmCatalog.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmCatalog.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmConstants.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmConstants.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AuditFilter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AuditFilter.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Address.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Address.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/collectionutil/Address.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Address.java diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Customer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Customer.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Email.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/Email.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Email.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Employee.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Employee.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java diff --git a/libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/io/FileMonitor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/io/FileMonitor.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleObject.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleObject.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/application/Application.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/application/Application.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/User.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/User.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java diff --git a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/Histogram.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/math3/Histogram.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/math3/Histogram.java diff --git a/flips/src/main/resources/logback.xml b/libraries-apache-commons/src/main/resources/logback.xml similarity index 100% rename from flips/src/main/resources/logback.xml rename to libraries-apache-commons/src/main/resources/logback.xml diff --git a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/FractionUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/FractionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/FractionUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/FractionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/DiffUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/DiffUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/DiffUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/DiffUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/StrBuilderUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/StrBuilderUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/WordUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/WordUtilsUnitTest.java diff --git a/libraries/src/test/resources/aaa.txt b/libraries-apache-commons/src/test/resources/aaa.txt similarity index 100% rename from libraries/src/test/resources/aaa.txt rename to libraries-apache-commons/src/test/resources/aaa.txt diff --git a/libraries/src/test/resources/book.csv b/libraries-apache-commons/src/test/resources/book.csv similarity index 100% rename from libraries/src/test/resources/book.csv rename to libraries-apache-commons/src/test/resources/book.csv diff --git a/libraries/src/test/resources/employees.sql b/libraries-apache-commons/src/test/resources/employees.sql similarity index 100% rename from libraries/src/test/resources/employees.sql rename to libraries-apache-commons/src/test/resources/employees.sql diff --git a/libraries/src/test/resources/fileTest.txt b/libraries-apache-commons/src/test/resources/fileTest.txt similarity index 100% rename from libraries/src/test/resources/fileTest.txt rename to libraries-apache-commons/src/test/resources/fileTest.txt diff --git a/libraries/src/test/resources/sample.txt b/libraries-apache-commons/src/test/resources/sample.txt similarity index 100% rename from libraries/src/test/resources/sample.txt rename to libraries-apache-commons/src/test/resources/sample.txt diff --git a/libraries-data/README.md b/libraries-data/README.md index 7e40a4a2e2..69856af66b 100644 --- a/libraries-data/README.md +++ b/libraries-data/README.md @@ -14,3 +14,4 @@ - [Building a Data Pipeline with Flink and Kafka](https://www.baeldung.com/kafka-flink-data-pipeline) - [Intro to Apache Storm](https://www.baeldung.com/apache-storm) - [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm) +- [Introduction to Kafka Connectors](https://www.baeldung.com/kafka-connectors-guide) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 54d24edbf6..daf6c8b500 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -429,13 +429,6 @@ - - - Apache Staging - https://repository.apache.org/content/groups/staging - - - 1.2.2 4.0.1 @@ -449,7 +442,7 @@ 2.8.2 1.1.0 1.5.0 - 2.8.5 + 2.9.7 3.0.0 3.6.2 3.8.4 diff --git a/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-sink.properties b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-sink.properties new file mode 100644 index 0000000000..594ccc6e95 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-sink.properties @@ -0,0 +1,20 @@ +# 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. + +name=local-file-sink +connector.class=FileStreamSink +tasks.max=1 +file=test.sink.txt +topics=connect-test \ No newline at end of file diff --git a/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-source.properties b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-source.properties new file mode 100644 index 0000000000..599cf4cb2a --- /dev/null +++ b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-source.properties @@ -0,0 +1,20 @@ +# 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. + +name=local-file-source +connector.class=FileStreamSource +tasks.max=1 +file=test.txt +topic=connect-test \ No newline at end of file diff --git a/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-standalone.properties b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-standalone.properties new file mode 100644 index 0000000000..a2369fa144 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-standalone.properties @@ -0,0 +1,44 @@ +# 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. + +# These are defaults. This file just demonstrates how to override some settings. +bootstrap.servers=localhost:9092 + +# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will +# need to configure these based on the format they want their data in when loaded from or stored into Kafka +key.converter=org.apache.kafka.connect.json.JsonConverter +value.converter=org.apache.kafka.connect.json.JsonConverter +# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply +# it to +key.converter.schemas.enable=false +value.converter.schemas.enable=false + +offset.storage.file.filename=/tmp/connect.offsets +# Flush much faster than normal, which is useful for testing/debugging +offset.flush.interval.ms=10000 + +# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins +# (connectors, converters, transformations). The list should consist of top level directories that include +# any combination of: +# a) directories immediately containing jars with plugins and their dependencies +# b) uber-jars with plugins and their dependencies +# c) directories immediately containing the package directory structure of classes of plugins and their dependencies +# Note: symlinks will be followed to discover dependencies or plugins. +# Examples: +# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors, +# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a +# directory other than the home directory of Confluent Platform. +plugin.path=C:\Software\confluent-5.0.0\share\java +#plugin.path=./share/java diff --git a/libraries-data/src/main/kafka-connect/02_Distributed/connect-distributed.properties b/libraries-data/src/main/kafka-connect/02_Distributed/connect-distributed.properties new file mode 100644 index 0000000000..5b91baddbd --- /dev/null +++ b/libraries-data/src/main/kafka-connect/02_Distributed/connect-distributed.properties @@ -0,0 +1,88 @@ +## +# 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. +## + +# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended +# to be used with the examples, and some settings may differ from those used in a production system, especially +# the `bootstrap.servers` and those specifying replication factors. + +# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. +bootstrap.servers=localhost:9092 + +# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs +group.id=connect-cluster + +# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will +# need to configure these based on the format they want their data in when loaded from or stored into Kafka +key.converter=org.apache.kafka.connect.json.JsonConverter +value.converter=org.apache.kafka.connect.json.JsonConverter +# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply +# it to +key.converter.schemas.enable=true +value.converter.schemas.enable=true + +# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted. +# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +offset.storage.topic=connect-offsets +offset.storage.replication.factor=1 +#offset.storage.partitions=25 + +# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, +# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +config.storage.topic=connect-configs +config.storage.replication.factor=1 + +# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted. +# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +status.storage.topic=connect-status +status.storage.replication.factor=1 +#status.storage.partitions=5 + +# Flush much faster than normal, which is useful for testing/debugging +offset.flush.interval.ms=10000 + +# These are provided to inform the user about the presence of the REST host and port configs +# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests. +#rest.host.name= +#rest.port=8083 + +# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers. +#rest.advertised.host.name= +#rest.advertised.port= + +# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins +# (connectors, converters, transformations). The list should consist of top level directories that include +# any combination of: +# a) directories immediately containing jars with plugins and their dependencies +# b) uber-jars with plugins and their dependencies +# c) directories immediately containing the package directory structure of classes of plugins and their dependencies +# Examples: +# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors, +# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a +# directory other than the home directory of Confluent Platform. +plugin.path=./share/java diff --git a/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-sink.json b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-sink.json new file mode 100644 index 0000000000..8902ecce52 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-sink.json @@ -0,0 +1,9 @@ +{ + "name": "local-file-sink", + "config": { + "connector.class": "FileStreamSink", + "tasks.max": 1, + "file": "test-distributed.sink.txt", + "topics": "connect-distributed" + } +} diff --git a/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-source.json b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-source.json new file mode 100644 index 0000000000..77e949c91b --- /dev/null +++ b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-source.json @@ -0,0 +1,9 @@ +{ + "name": "local-file-source", + "config": { + "connector.class": "FileStreamSource", + "tasks.max": 1, + "file": "test-distributed.txt", + "topic": "connect-distributed" + } +} diff --git a/libraries-data/src/main/kafka-connect/03_Transform/connect-distributed.properties b/libraries-data/src/main/kafka-connect/03_Transform/connect-distributed.properties new file mode 100644 index 0000000000..fa63be24b8 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/03_Transform/connect-distributed.properties @@ -0,0 +1,88 @@ +## +# 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. +## + +# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended +# to be used with the examples, and some settings may differ from those used in a production system, especially +# the `bootstrap.servers` and those specifying replication factors. + +# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. +bootstrap.servers=localhost:9092 + +# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs +group.id=connect-cluster + +# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will +# need to configure these based on the format they want their data in when loaded from or stored into Kafka +key.converter=org.apache.kafka.connect.json.JsonConverter +value.converter=org.apache.kafka.connect.json.JsonConverter +# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply +# it to +key.converter.schemas.enable=false +value.converter.schemas.enable=false + +# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted. +# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +offset.storage.topic=connect-offsets +offset.storage.replication.factor=1 +#offset.storage.partitions=25 + +# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, +# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +config.storage.topic=connect-configs +config.storage.replication.factor=1 + +# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted. +# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +status.storage.topic=connect-status +status.storage.replication.factor=1 +#status.storage.partitions=5 + +# Flush much faster than normal, which is useful for testing/debugging +offset.flush.interval.ms=10000 + +# These are provided to inform the user about the presence of the REST host and port configs +# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests. +#rest.host.name= +#rest.port=8083 + +# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers. +#rest.advertised.host.name= +#rest.advertised.port= + +# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins +# (connectors, converters, transformations). The list should consist of top level directories that include +# any combination of: +# a) directories immediately containing jars with plugins and their dependencies +# b) uber-jars with plugins and their dependencies +# c) directories immediately containing the package directory structure of classes of plugins and their dependencies +# Examples: +# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors, +# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a +# directory other than the home directory of Confluent Platform. +plugin.path=./share/java diff --git a/libraries-data/src/main/kafka-connect/03_Transform/connect-file-source-transform.json b/libraries-data/src/main/kafka-connect/03_Transform/connect-file-source-transform.json new file mode 100644 index 0000000000..e5e21a0608 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/03_Transform/connect-file-source-transform.json @@ -0,0 +1,15 @@ +{ + "name": "local-file-source", + "config": { + "connector.class": "FileStreamSource", + "tasks.max": 1, + "file": "transformation.txt", + "topic": "connect-transformation", + "transforms": "MakeMap,InsertSource", + "transforms.MakeMap.type": "org.apache.kafka.connect.transforms.HoistField$Value", + "transforms.MakeMap.field": "line", + "transforms.InsertSource.type": "org.apache.kafka.connect.transforms.InsertField$Value", + "transforms.InsertSource.static.field": "data_source", + "transforms.InsertSource.static.value": "test-file-source" + } +} diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties b/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties new file mode 100644 index 0000000000..5b91baddbd --- /dev/null +++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties @@ -0,0 +1,88 @@ +## +# 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. +## + +# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended +# to be used with the examples, and some settings may differ from those used in a production system, especially +# the `bootstrap.servers` and those specifying replication factors. + +# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. +bootstrap.servers=localhost:9092 + +# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs +group.id=connect-cluster + +# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will +# need to configure these based on the format they want their data in when loaded from or stored into Kafka +key.converter=org.apache.kafka.connect.json.JsonConverter +value.converter=org.apache.kafka.connect.json.JsonConverter +# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply +# it to +key.converter.schemas.enable=true +value.converter.schemas.enable=true + +# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted. +# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +offset.storage.topic=connect-offsets +offset.storage.replication.factor=1 +#offset.storage.partitions=25 + +# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, +# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +config.storage.topic=connect-configs +config.storage.replication.factor=1 + +# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted. +# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create +# the topic before starting Kafka Connect if a specific topic configuration is needed. +# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value. +# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able +# to run this example on a single-broker cluster and so here we instead set the replication factor to 1. +status.storage.topic=connect-status +status.storage.replication.factor=1 +#status.storage.partitions=5 + +# Flush much faster than normal, which is useful for testing/debugging +offset.flush.interval.ms=10000 + +# These are provided to inform the user about the presence of the REST host and port configs +# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests. +#rest.host.name= +#rest.port=8083 + +# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers. +#rest.advertised.host.name= +#rest.advertised.port= + +# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins +# (connectors, converters, transformations). The list should consist of top level directories that include +# any combination of: +# a) directories immediately containing jars with plugins and their dependencies +# b) uber-jars with plugins and their dependencies +# c) directories immediately containing the package directory structure of classes of plugins and their dependencies +# Examples: +# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors, +# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a +# directory other than the home directory of Confluent Platform. +plugin.path=./share/java diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json b/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json new file mode 100644 index 0000000000..333768e4b7 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json @@ -0,0 +1,22 @@ +{ + "firstName": "John", + "lastName": "Smith", + "age": 25, + "address": { + "streetAddress": "21 2nd Street", + "city": "New York", + "state": "NY", + "postalCode": "10021" + }, + "phoneNumber": [{ + "type": "home", + "number": "212 555-1234" + }, { + "type": "fax", + "number": "646 555-4567" + } + ], + "gender": { + "type": "male" + } +} diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json b/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json new file mode 100644 index 0000000000..02d87c5ad7 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json @@ -0,0 +1,11 @@ +{ + "name": "mqtt-source", + "config": { + "connector.class": "io.confluent.connect.mqtt.MqttSourceConnector", + "tasks.max": 1, + "mqtt.server.uri": "ws://broker.hivemq.com:8000/mqtt", + "mqtt.topics": "baeldung", + "kafka.topic": "connect-custom", + "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter" + } +} diff --git a/libraries-data/src/main/resources/logback.xml b/libraries-data/src/main/resources/logback.xml index a57d22fcb2..3d2ec51566 100644 --- a/libraries-data/src/main/resources/logback.xml +++ b/libraries-data/src/main/resources/logback.xml @@ -9,7 +9,7 @@ - + \ No newline at end of file diff --git a/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java index 96ed090482..9db7bdb4ac 100644 --- a/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jmapper/JMapperIntegrationTest.java @@ -15,100 +15,88 @@ import com.googlecode.jmapper.api.JMapperAPI; public class JMapperIntegrationTest { - @Test - public void givenUser_whenUseAnnotation_thenConverted(){ + public void givenUser_whenUseAnnotation_thenConverted() { JMapper userMapper = new JMapper<>(UserDto.class, User.class); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); + + User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20)); UserDto result = userMapper.getDestination(user); - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getUsername()); - } - - @Test - public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){ - JMapper userMapper= new JMapper<>(UserDto1.class, User.class); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto1 result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getEmail()); - } - - @Test - public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){ - JMapper userMapper = new JMapper<>(UserDto.class, User.class); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getUsername()); - assertTrue(result.getAge() > 0); - } - - //======================= XML - - @Test - public void givenUser_whenUseXml_thenConverted(){ - JMapper userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml"); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getUsername()); - } - - @Test - public void givenUser_whenUseXmlGlobal_thenConverted(){ - JMapper userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml"); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto1 result = userMapper.getDestination(user); - - System.out.println(result); - assertEquals(user.getId(), result.getId()); - assertEquals(user.getEmail(), result.getEmail()); - } - - // ===== API - - @Test - public void givenUser_whenUseApi_thenConverted(){ - JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) - .add(attribute("id").value("id")) - .add(attribute("username").value("email")) - ) ; - JMapper userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto result = userMapper.getDestination(user); - - System.out.println(result); assertEquals(user.getId(), result.getId()); assertEquals(user.getEmail(), result.getUsername()); } - - @Test - public void givenUser_whenUseApiGlobal_thenConverted(){ - JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class) - .add(global()) - ) ; - JMapper userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi); - - User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20)); - UserDto1 result = userMapper1.getDestination(user); - System.out.println(result); + @Test + public void givenUser_whenUseGlobalMapAnnotation_thenConverted() { + JMapper userMapper = new JMapper<>(UserDto1.class, User.class); + + User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20)); + UserDto1 result = userMapper.getDestination(user); + assertEquals(user.getId(), result.getId()); assertEquals(user.getEmail(), result.getEmail()); } + + @Test + public void givenUser_whenUseAnnotationExplicitConversion_thenConverted() { + JMapper userMapper = new JMapper<>(UserDto.class, User.class); + + User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20)); + UserDto result = userMapper.getDestination(user); + + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + assertTrue(result.getAge() > 0); + } + + // ======================= XML + + @Test + public void givenUser_whenUseXml_thenConverted() { + JMapper userMapper = new JMapper<>(UserDto.class, User.class, "user_jmapper.xml"); + + User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20)); + UserDto result = userMapper.getDestination(user); + + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseXmlGlobal_thenConverted() { + JMapper userMapper = new JMapper<>(UserDto1.class, User.class, "user_jmapper1.xml"); + + User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20)); + UserDto1 result = userMapper.getDestination(user); + + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } + + // ===== API + + @Test + public void givenUser_whenUseApi_thenConverted() { + JMapperAPI jmapperApi = new JMapperAPI().add(mappedClass(UserDto.class).add(attribute("id").value("id")).add(attribute("username").value("email"))); + JMapper userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi); + + User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20)); + UserDto result = userMapper.getDestination(user); + + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getUsername()); + } + + @Test + public void givenUser_whenUseApiGlobal_thenConverted() { + JMapperAPI jmapperApi = new JMapperAPI().add(mappedClass(UserDto.class).add(global())); + JMapper userMapper1 = new JMapper<>(UserDto1.class, User.class, jmapperApi); + + User user = new User(1L, "john@test.com", LocalDate.of(1980, 8, 20)); + UserDto1 result = userMapper1.getDestination(user); + + assertEquals(user.getId(), result.getId()); + assertEquals(user.getEmail(), result.getEmail()); + } + } diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index 6fca09faf4..661f5f01d5 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -1,9 +1,10 @@ 4.0.0 - com.baeldung libraries-server 0.0.1-SNAPSHOT + libraries-server + com.baeldung parent-modules diff --git a/libraries/README.md b/libraries/README.md index 851e3a3d17..b247caedda 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -1,40 +1,28 @@ ### Relevant articles - [Intro to Jasypt](http://www.baeldung.com/jasypt) -- [Array Processing with Apache Commons Lang 3](http://www.baeldung.com/array-processing-commons-lang) -- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) - [Introduction to Javatuples](http://www.baeldung.com/java-tuples) - [Introduction to Javassist](http://www.baeldung.com/javassist) - [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink) - [Introduction to JSONassert](http://www.baeldung.com/jsonassert) - [Intro to JaVers](http://www.baeldung.com/javers) -- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) - [Introduction to Quartz](http://www.baeldung.com/quartz) - [How to Warm Up the JVM](http://www.baeldung.com/java-jvm-warmup) -- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) - [Software Transactional Memory in Java Using Multiverse](http://www.baeldung.com/java-multiverse-stm) - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) -- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) -- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) -- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Introduction to Neuroph](http://www.baeldung.com/neuroph) -- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) -- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) - [Introduction to PCollections](http://www.baeldung.com/java-pcollections) - [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly) -- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) - [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections) - [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by) -- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) - [Introduction to NoException](http://www.baeldung.com/no-exception) -- [Apache Commons IO](http://www.baeldung.com/apache-commons-io) - [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types) - [Introduction to javax.measure](http://www.baeldung.com/javax-measure) - [Spring Yarg Integration](http://www.baeldung.com/spring-yarg) @@ -44,9 +32,7 @@ - [Introduction to MBassador](http://www.baeldung.com/mbassador) - [Introduction to Retrofit](http://www.baeldung.com/retrofit) - [Using Pairs in Java](http://www.baeldung.com/java-pairs) -- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) - [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine) -- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [Introduction To Docx4J](http://www.baeldung.com/docx4j) - [Introduction to StreamEx](http://www.baeldung.com/streamex) - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) @@ -62,28 +48,23 @@ - [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) -- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) - [Introduction to jOOL](http://www.baeldung.com/jool) - [Consumer Driven Contracts with Pact](http://www.baeldung.com/pact-junit-consumer-driven-contracts) -- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils) -- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map) - [Introduction to Atlassian Fugue](http://www.baeldung.com/java-fugue) - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) -- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) - [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) - [Introduction to JavaPoet](http://www.baeldung.com/java-poet) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time) -- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) -- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) - [Guide to Resilience4j](http://www.baeldung.com/resilience4j) - [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml) - [Guide to JMapper](http://www.baeldung.com/jmapper) -- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) - [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) +- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) +- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 8ffd33272d..c7ef64bc59 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -50,31 +50,21 @@ opencsv ${opencsv.version} - - commons-beanutils - commons-beanutils - ${commons-beanutils.version} - org.apache.commons commons-lang3 ${commons-lang.version} - org.apache.commons - commons-text - ${commons-text.version} + commons-net + commons-net + ${commons-net.version} tec.units unit-ri ${unit-ri.version} - - org.apache.commons - commons-collections4 - ${commons.collections.version} - org.jasypt jasypt @@ -134,42 +124,16 @@ - - commons-io - commons-io - ${commons.io.version} - - - commons-chain - commons-chain - ${commons-chain.version} - - - org.apache.commons - commons-csv - ${commons-csv.version} - - - commons-dbutils - commons-dbutils - ${commons.dbutils.version} - - - - org.apache.commons - commons-math3 - ${common-math3.version} - net.serenity-bdd serenity-core ${serenity.version} test - - org.asciidoctor - asciidoctorj - + + org.asciidoctor + asciidoctorj + @@ -613,7 +577,7 @@ test test - + org.milyn milyn-smooks-all @@ -675,24 +639,6 @@ resilience4j-timelimiter ${resilience4j.version} - - org.knowm.xchart - xchart - ${xchart-version} - - - - commons-net - commons-net - ${commons-net.version} - - - org.mockftpserver - MockFtpServer - ${mockftpserver.version} - test - - com.squareup javapoet @@ -708,8 +654,8 @@ org.yaml snakeyaml - ${snakeyaml.version} - + ${snakeyaml.version} + com.numericalmethod @@ -717,14 +663,21 @@ ${suanshu.version} + + org.derive4j + derive4j + ${derive4j.version} + true + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + - - maven2-repository.dev.java.net - Java.net repository - http://download.java.net/maven/2 - false @@ -854,10 +807,6 @@ 0.7.0 3.2.7 3.6 - 1.1 - 1.9.3 - 1.2 - 1.4 1.9.2 1.2 3.21.0-GA @@ -865,21 +814,17 @@ 1.5.0 3.1.0 4.5.3 - 2.5 - 1.6 1.4.196 1.0 4.5.3 - 2.5 - 2.8.5 + 2.9.7 2.92 1.9.26 1.41.0 1.9.0 1.9.27 1.1.0 - 4.1 4.12 0.10 3.5.0 @@ -917,13 +862,9 @@ 2.1.2 2.5.11 0.12.1 - 3.5.2 - 3.6 - 2.7.1 1.10.0 1.3 0.8.1 - 3.6.1 3.2.0-m7 5.1.1 5.0.2 @@ -942,7 +883,7 @@ 2.0.4 1.3.1 1.2.6 - 4.7 + 4.8.1 1.0.1 3.3.5 2.1 @@ -952,6 +893,9 @@ 4.5.1 3.3.0 3.0.2 + 1.1.0 + 2.7.1 + 3.6 diff --git a/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java new file mode 100644 index 0000000000..d22bb89fe2 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java @@ -0,0 +1,10 @@ +package com.baeldung.derive4j.adt; + +import org.derive4j.Data; + +import java.util.function.Function; + +@Data +interface Either{ + X match(Function left, Function right); +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java new file mode 100644 index 0000000000..9f53f3d25b --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java @@ -0,0 +1,21 @@ +package com.baeldung.derive4j.lazy; + +import org.derive4j.Data; +import org.derive4j.Derive; +import org.derive4j.Make; + +@Data(value = @Derive( + inClass = "{ClassName}Impl", + make = {Make.lazyConstructor, Make.constructors} +)) +public interface LazyRequest { + interface Cases{ + R GET(String path); + R POST(String path, String body); + R PUT(String path, String body); + R DELETE(String path); + } + + R match(LazyRequest.Cases method); +} + diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java new file mode 100644 index 0000000000..04d630f1ef --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java @@ -0,0 +1,15 @@ +package com.baeldung.derive4j.pattern; + +import org.derive4j.Data; + +@Data +interface HTTPRequest { + interface Cases{ + R GET(String path); + R POST(String path, String body); + R PUT(String path, String body); + R DELETE(String path); + } + + R match(Cases method); +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java new file mode 100644 index 0000000000..593f94a8b7 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java @@ -0,0 +1,19 @@ +package com.baeldung.derive4j.pattern; + +public class HTTPResponse { + private int statusCode; + private String responseBody; + + public int getStatusCode() { + return statusCode; + } + + public String getResponseBody() { + return responseBody; + } + + public HTTPResponse(int statusCode, String responseBody) { + this.statusCode = statusCode; + this.responseBody = responseBody; + } +} diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java new file mode 100644 index 0000000000..53f4af628c --- /dev/null +++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java @@ -0,0 +1,17 @@ +package com.baeldung.derive4j.pattern; + + +public class HTTPServer { + public static String GET_RESPONSE_BODY = "Success!"; + public static String PUT_RESPONSE_BODY = "Resource Created!"; + public static String POST_RESPONSE_BODY = "Resource Updated!"; + public static String DELETE_RESPONSE_BODY = "Resource Deleted!"; + + public HTTPResponse acceptRequest(HTTPRequest request) { + return HTTPRequests.caseOf(request) + .GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY)) + .POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY)) + .PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY)) + .DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY)); + } +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java new file mode 100644 index 0000000000..511e24961f --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.derive4j.adt; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Optional; +import java.util.function.Function; +@RunWith(MockitoJUnitRunner.class) +public class EitherUnitTest { + @Test + public void testEitherIsCreatedFromRight() { + Either either = Eithers.right("Okay"); + Optional leftOptional = Eithers.getLeft(either); + Optional rightOptional = Eithers.getRight(either); + Assertions.assertThat(leftOptional).isEmpty(); + Assertions.assertThat(rightOptional).hasValue("Okay"); + + } + + @Test + public void testEitherIsMatchedWithRight() { + Either either = Eithers.right("Okay"); + Function leftFunction = Mockito.mock(Function.class); + Function rightFunction = Mockito.mock(Function.class); + either.match(leftFunction, rightFunction); + Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay"); + Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java new file mode 100644 index 0000000000..3830bc52d0 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.derive4j.lazy; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.function.Supplier; + +public class LazyRequestUnitTest { + + @Test + public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() { + LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier()); + + LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get()); + Mockito.verify(mockSupplier, Mockito.times(0)).get(); + Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get"); + Mockito.verify(mockSupplier, Mockito.times(1)).get(); + + } + + class LazyRequestSupplier implements Supplier { + @Override + public LazyRequest get() { + return LazyRequestImpl.GET("http://test.com/get"); + } + } +} diff --git a/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java new file mode 100644 index 0000000000..0fc257742a --- /dev/null +++ b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.derive4j.pattern; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class HTTPRequestUnitTest { + public static HTTPServer server; + + @BeforeClass + public static void setUp() { + server = new HTTPServer(); + } + + @Test + public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() { + HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource"); + HTTPResponse response = server.acceptRequest(postRequest); + Assert.assertEquals(201, response.getStatusCode()); + Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody()); + } +} diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java index d62a115abd..97ead07470 100644 --- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java +++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java @@ -1,79 +1,116 @@ -package com.baeldung.fj; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import fj.F; -import fj.data.Array; -import fj.data.List; -import fj.data.Option; -import fj.function.Characters; -import fj.function.Integers; - -public class FunctionalJavaUnitTest { - - public static final F isEven = i -> i % 2 == 0; - - @Test - public void calculateEvenNumbers_givenIntList_returnTrue() { - List fList = List.list(3, 4, 5, 6); - List evenList = fList.map(isEven); - List evenListTrueResult = List.list(false, true, false, true); - List evenListFalseResult = List.list(true, false, false, true); - assertEquals(evenList.equals(evenListTrueResult), true); - assertEquals(evenList.equals(evenListFalseResult), false); - } - - @Test - public void mapList_givenIntList_returnResult() { - List fList = List.list(3, 4, 5, 6); - fList = fList.map(i -> i + 100); - List resultList = List.list(103, 104, 105, 106); - List falseResultList = List.list(15, 504, 105, 106); - assertEquals(fList.equals(resultList), true); - assertEquals(fList.equals(falseResultList), false); - } - - @Test - public void filterList_givenIntList_returnResult() { - Array array = Array.array(3, 4, 5, 6); - Array filteredArray = array.filter(Integers.even); - Array result = Array.array(4, 6); - Array wrongResult = Array.array(3, 5); - assertEquals(filteredArray.equals(result), true); - assertEquals(filteredArray.equals(wrongResult), false); - } - - @Test - public void checkForLowerCase_givenStringArray_returnResult() { - Array array = Array.array("Welcome", "To", "baeldung"); - Array array2 = Array.array("Welcome", "To", "Baeldung"); - Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); - Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); - assertEquals(isExist, true); - assertEquals(isExist2, false); - } - - @Test - public void checkOptions_givenOptions_returnResult() { - Option n1 = Option.some(1); - Option n2 = Option.some(2); - - F> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none(); - - Option result1 = n1.bind(f1); - Option result2 = n2.bind(f1); - - assertEquals(result1, Option.none()); - assertEquals(result2, Option.some(102)); - } - - @Test - public void foldLeft_givenArray_returnResult() { - Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); - int sum = intArray.foldLeft(Integers.add, 0); - assertEquals(sum, 260); - } - -} +package com.baeldung.fj; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +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 FunctionalJavaUnitTest { + + public static final F isEven = i -> i % 2 == 0; + + public static final Integer timesTwoRegular(Integer i) { + return i * 2; + } + + public static final F timesTwo = i -> i * 2; + + public static final F plusOne = i -> i + 1; + + @Test + public void multiplyNumbers_givenIntList_returnTrue() { + List fList = List.list(1, 2, 3, 4); + List fList1 = fList.map(timesTwo); + List fList2 = fList.map(i -> i * 2); + + assertTrue(fList1.equals(fList2)); + } + + @Test + public void applyMultipleFunctions_givenIntList_returnFalse() { + List fList = List.list(1, 2, 3, 4); + List fList1 = fList.map(timesTwo).map(plusOne); + Show.listShow(Show.intShow).println(fList1); + List fList2 = fList.map(plusOne).map(timesTwo); + Show.listShow(Show.intShow).println(fList2); + + assertFalse(fList1.equals(fList2)); + } + + @Test + public void calculateEvenNumbers_givenIntList_returnTrue() { + List fList = List.list(3, 4, 5, 6); + List evenList = fList.map(isEven); + List evenListTrueResult = List.list(false, true, false, true); + + assertTrue(evenList.equals(evenListTrueResult)); + } + + @Test + public void mapList_givenIntList_returnResult() { + List fList = List.list(3, 4, 5, 6); + fList = fList.map(i -> i + 100); + List resultList = List.list(103, 104, 105, 106); + + assertTrue(fList.equals(resultList)); + } + + @Test + public void filterList_givenIntList_returnResult() { + Array array = Array.array(3, 4, 5, 6); + Array filteredArray = array.filter(isEven); + Array result = Array.array(4, 6); + + assertTrue(filteredArray.equals(result)); + } + + @Test + public void checkForLowerCase_givenStringArray_returnResult() { + Array array = Array.array("Welcome", "To", "baeldung"); + assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase))); + + Array array2 = Array.array("Welcome", "To", "Baeldung"); + assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase))); + + assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase))); + } + + @Test + public void checkOptions_givenOptions_returnResult() { + Option n1 = Option.some(1); + Option n2 = Option.some(2); + Option n3 = Option.none(); + + F> function = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none(); + + Option result1 = n1.bind(function); + Option result2 = n2.bind(function); + Option result3 = n3.bind(function); + + assertEquals(Option.none(), result1); + assertEquals(Option.some(102), result2); + assertEquals(Option.none(), result3); + } + + @Test + public void foldLeft_givenArray_returnResult() { + Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); + int sumAll = intArray.foldLeft(Integers.add, 0); + + assertEquals(260, sumAll); + + int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0); + + assertEquals(148, sumEven); + } + +} diff --git a/linkrest/pom.xml b/linkrest/pom.xml index a27caea1ff..073a173aff 100644 --- a/linkrest/pom.xml +++ b/linkrest/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.baeldung linkrest 0.0.1-SNAPSHOT + linkrest war diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index 8e9968085e..3031274d0b 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -103,7 +103,7 @@ 3.3.6 3.3.0.Final 3.1.0 - 2.8.5 + 2.9.7 2.4 diff --git a/logging-modules/log4j/pom.xml b/logging-modules/log4j/pom.xml index 432295fc62..af97d812de 100644 --- a/logging-modules/log4j/pom.xml +++ b/logging-modules/log4j/pom.xml @@ -1,10 +1,12 @@ - 4.0.0 com.baeldung log4j 1.0-SNAPSHOT + log4j com.baeldung diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index 65da318636..924abfd346 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 log4j2 - + log4j2 + com.baeldung parent-modules @@ -114,7 +115,7 @@ - 2.9.5 + 2.9.7 1.4.193 2.1.1 2.11.0 diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index e917754b3c..ef7adbc3ea 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -42,7 +42,7 @@ 1.2.3 0.1.5 - 2.9.3 + 2.9.7 diff --git a/lombok-custom/pom.xml b/lombok-custom/pom.xml new file mode 100644 index 0000000000..41bd042a5e --- /dev/null +++ b/lombok-custom/pom.xml @@ -0,0 +1,58 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + 4.0.0 + lombok-custom + 0.1-SNAPSHOT + + + + org.projectlombok + lombok + 1.14.8 + provided + + + + org.kohsuke.metainf-services + metainf-services + 1.8 + + + + org.eclipse.jdt + core + 3.3.0-v_771 + + + + + + default-tools.jar + + + java.vendor + Oracle Corporation + + + + + com.sun + tools + ${java.version} + system + ${java.home}/../lib/tools.jar + + + + + + + \ No newline at end of file diff --git a/lombok-custom/src/main/java/com/baeldung/singleton/Singleton.java b/lombok-custom/src/main/java/com/baeldung/singleton/Singleton.java new file mode 100644 index 0000000000..2d2fd0ffb9 --- /dev/null +++ b/lombok-custom/src/main/java/com/baeldung/singleton/Singleton.java @@ -0,0 +1,10 @@ +package com.baeldung.singleton; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +public @interface Singleton { + + +} diff --git a/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonEclipseHandler.java b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonEclipseHandler.java new file mode 100644 index 0000000000..03cdd707a4 --- /dev/null +++ b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonEclipseHandler.java @@ -0,0 +1,124 @@ +package com.baeldung.singleton.handlers; + +import com.baeldung.singleton.Singleton; +import lombok.core.AnnotationValues; +import lombok.eclipse.EclipseAnnotationHandler; +import lombok.eclipse.EclipseNode; +import lombok.eclipse.handlers.EclipseHandlerUtil; +import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; +import org.eclipse.jdt.internal.compiler.ast.Annotation; +import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; +import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; +import org.eclipse.jdt.internal.compiler.ast.FieldReference; +import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; +import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.jdt.internal.compiler.ast.Statement; +import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.jdt.internal.compiler.ast.TypeReference; +import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; +import org.kohsuke.MetaInfServices; + +import static lombok.eclipse.Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; +import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccFinal; +import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccPrivate; +import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccStatic; + +@MetaInfServices(EclipseAnnotationHandler.class) +public class SingletonEclipseHandler extends EclipseAnnotationHandler { + + + @Override + public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { + + //remove annotation + EclipseHandlerUtil.unboxAndRemoveAnnotationParameter(ast, "onType", "@Singleton(onType=", annotationNode); + + //add private constructor + EclipseNode singletonClass = annotationNode.up(); + + TypeDeclaration singletonClassType = (TypeDeclaration) singletonClass.get(); + ConstructorDeclaration constructor = addConstructor(singletonClass, singletonClassType); + + TypeReference singletonTypeRef = EclipseHandlerUtil.cloneSelfType(singletonClass, singletonClassType); + + //add inner class + + //add instance field + StringBuilder sb = new StringBuilder(); + sb.append(singletonClass.getName()); + sb.append("Holder"); + String innerClassName = sb.toString(); + TypeDeclaration innerClass = new TypeDeclaration(singletonClassType.compilationResult); + innerClass.modifiers = AccPrivate | AccStatic; + innerClass.name = innerClassName.toCharArray(); + + FieldDeclaration instanceVar = addInstanceVar(constructor, singletonTypeRef, innerClass); + + FieldDeclaration[] declarations = new FieldDeclaration[]{instanceVar}; + innerClass.fields = declarations; + + EclipseHandlerUtil.injectType(singletonClass, innerClass); + + addFactoryMethod(singletonClass, singletonClassType, singletonTypeRef, innerClass, instanceVar); + + + } + + private void addFactoryMethod(EclipseNode singletonClass, TypeDeclaration astNode, TypeReference typeReference, TypeDeclaration innerClass, FieldDeclaration field) { + MethodDeclaration factoryMethod = new MethodDeclaration(astNode.compilationResult); + factoryMethod.modifiers = AccStatic | ClassFileConstants.AccPublic; + factoryMethod.returnType = typeReference; + factoryMethod.sourceStart = astNode.sourceStart; + factoryMethod.sourceEnd = astNode.sourceEnd; + factoryMethod.selector = "getInstance".toCharArray(); + factoryMethod.bits = ECLIPSE_DO_NOT_TOUCH_FLAG; + + long pS = factoryMethod.sourceStart; + long pE = factoryMethod.sourceEnd; + long p = (long) pS << 32 | pE; + + FieldReference ref = new FieldReference(field.name, p); + ref.receiver = new SingleNameReference(innerClass.name, p); + + ReturnStatement statement = new ReturnStatement(ref, astNode.sourceStart, astNode.sourceEnd); + + factoryMethod.statements = new Statement[]{statement}; + + EclipseHandlerUtil.injectMethod(singletonClass, factoryMethod); + } + + private FieldDeclaration addInstanceVar(ConstructorDeclaration constructor, TypeReference typeReference, TypeDeclaration innerClass) { + FieldDeclaration field = new FieldDeclaration(); + field.modifiers = AccPrivate | AccStatic | AccFinal; + field.name = "INSTANCE".toCharArray(); + + field.type = typeReference; + + AllocationExpression exp = new AllocationExpression(); + exp.type = typeReference; + exp.binding = constructor.binding; + exp.sourceStart = innerClass.sourceStart; + exp.sourceEnd = innerClass.sourceEnd; + + field.initialization = exp; + return field; + } + + private ConstructorDeclaration addConstructor(EclipseNode singletonClass, TypeDeclaration astNode) { + ConstructorDeclaration constructor = new ConstructorDeclaration(astNode.compilationResult); + constructor.modifiers = AccPrivate; + constructor.selector = astNode.name; + constructor.sourceStart = astNode.sourceStart; + constructor.sourceEnd = astNode.sourceEnd; + constructor.thrownExceptions = null; + constructor.typeParameters = null; + constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; + constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = astNode.sourceStart; + constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = astNode.sourceEnd; + constructor.arguments = null; + + EclipseHandlerUtil.injectMethod(singletonClass, constructor); + return constructor; + } +} diff --git a/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonJavacHandler.java b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonJavacHandler.java new file mode 100644 index 0000000000..1f4cf0ea58 --- /dev/null +++ b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonJavacHandler.java @@ -0,0 +1,108 @@ +package com.baeldung.singleton.handlers; + +import com.baeldung.singleton.Singleton; +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.ListBuffer; +import lombok.core.AnnotationValues; +import lombok.javac.Javac8BasedLombokOptions; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; +import lombok.javac.JavacTreeMaker; +import lombok.javac.handlers.JavacHandlerUtil; +import org.kohsuke.MetaInfServices; + +import static lombok.javac.handlers.JavacHandlerUtil.deleteAnnotationIfNeccessary; +import static lombok.javac.handlers.JavacHandlerUtil.deleteImportFromCompilationUnit; + +@MetaInfServices(JavacAnnotationHandler.class) +public class SingletonJavacHandler extends JavacAnnotationHandler { + + @Override + public void handle(AnnotationValues annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) { + + Context context = annotationNode.getContext(); + + Javac8BasedLombokOptions options = Javac8BasedLombokOptions.replaceWithDelombokOptions(context); + options.deleteLombokAnnotations(); + + //remove annotation + deleteAnnotationIfNeccessary(annotationNode, Singleton.class); + //remove import + deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); + + //private constructor + JavacNode singletonClass = annotationNode.up(); + JavacTreeMaker singletonClassTreeMaker = singletonClass.getTreeMaker(); + + addPrivateConstructor(singletonClass, singletonClassTreeMaker); + + //singleton holder + JavacNode holderInnerClass = addInnerClass(singletonClass, singletonClassTreeMaker); + + //inject static field to this + addInstanceVar(singletonClass, singletonClassTreeMaker, holderInnerClass); + + //add factory method + addFactoryMethod(singletonClass, singletonClassTreeMaker, holderInnerClass); + } + + private void addFactoryMethod(JavacNode singletonClass, JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) { + JCTree.JCModifiers modifiers = singletonClassTreeMaker.Modifiers(Flags.PUBLIC | Flags.STATIC); + + JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get(); + JCTree.JCIdent singletonClassType = singletonClassTreeMaker.Ident(singletonClassDecl.name); + + JCTree.JCBlock block = addReturnBlock(singletonClassTreeMaker, holderInnerClass); + + JCTree.JCMethodDecl factoryMethod = singletonClassTreeMaker.MethodDef(modifiers, singletonClass.toName("getInstance"), singletonClassType, List.nil(), List.nil(), List.nil(), block, null); + JavacHandlerUtil.injectMethod(singletonClass, factoryMethod); + } + + private JCTree.JCBlock addReturnBlock(JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) { + + JCTree.JCClassDecl holderInnerClassDecl = (JCTree.JCClassDecl) holderInnerClass.get(); + JavacTreeMaker holderInnerClassTreeMaker = holderInnerClass.getTreeMaker(); + JCTree.JCIdent holderInnerClassType = holderInnerClassTreeMaker.Ident(holderInnerClassDecl.name); + + JCTree.JCFieldAccess instanceVarAccess = holderInnerClassTreeMaker.Select(holderInnerClassType, holderInnerClass.toName("INSTANCE")); + JCTree.JCReturn returnValue = singletonClassTreeMaker.Return(instanceVarAccess); + + ListBuffer statements = new ListBuffer<>(); + statements.append(returnValue); + + return singletonClassTreeMaker.Block(0L, statements.toList()); + } + + + private void addInstanceVar(JavacNode singletonClass, JavacTreeMaker singletonClassTM, JavacNode holderClass) { + JCTree.JCModifiers fieldMod = singletonClassTM.Modifiers(Flags.PRIVATE | Flags.STATIC | Flags.FINAL); + + JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get(); + JCTree.JCIdent singletonClassType = singletonClassTM.Ident(singletonClassDecl.name); + + JCTree.JCNewClass newKeyword = singletonClassTM.NewClass(null, List.nil(), singletonClassType, List.nil(), null); + + JCTree.JCVariableDecl instanceVar = singletonClassTM.VarDef(fieldMod, singletonClass.toName("INSTANCE"), singletonClassType, newKeyword); + JavacHandlerUtil.injectField(holderClass, instanceVar); + } + + private JavacNode addInnerClass(JavacNode singletonClass, JavacTreeMaker singletonTM) { + JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE | Flags.STATIC); + String innerClassName = singletonClass.getName() + "Holder"; + JCTree.JCClassDecl innerClassDecl = singletonTM.ClassDef(modifiers, singletonClass.toName(innerClassName), List.nil(), null, List.nil(), List.nil()); + return JavacHandlerUtil.injectType(singletonClass, innerClassDecl); + } + + private void addPrivateConstructor(JavacNode singletonClass, JavacTreeMaker singletonTM) { + JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE); + JCTree.JCBlock block = singletonTM.Block(0L, List.nil()); + JCTree.JCMethodDecl constructor = singletonTM.MethodDef(modifiers, singletonClass.toName(""), null, List.nil(), List.nil(), List.nil(), block, null); + + JavacHandlerUtil.injectMethod(singletonClass, constructor); + } + + +} diff --git a/maven-archetype/pom.xml b/maven-archetype/pom.xml index f7871c81ea..73ddc78fc7 100644 --- a/maven-archetype/pom.xml +++ b/maven-archetype/pom.xml @@ -5,9 +5,10 @@ com.baeldung.archetypes maven-archetype 1.0-SNAPSHOT + maven-archetype maven-archetype Archetype used to generate rest application based on jaxrs 2.1 - + diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index d5c5b7ab55..fe1e025d1f 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -3,11 +3,11 @@ 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 - com.baeldung.maven.polyglot maven-polyglot-json-extension 1.0-SNAPSHOT - + maven-polyglot-json-extension + 1.8 1.8 diff --git a/maven/pom.xml b/maven/pom.xml index 4bec533226..01fd28db74 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -4,6 +4,7 @@ com.baeldung maven 0.0.1-SNAPSHOT + maven war diff --git a/maven/versions-maven-plugin/pom.xml b/maven/versions-maven-plugin/pom.xml index 295c77b860..dc0cba75f9 100644 --- a/maven/versions-maven-plugin/pom.xml +++ b/maven/versions-maven-plugin/pom.xml @@ -3,9 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - versions-maven-plugin-example + versions-maven-plugin 0.0.1-SNAPSHOT - + versions-maven-plugin + 1.15 diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml index f92c00892b..dee8eca10d 100644 --- a/mesos-marathon/pom.xml +++ b/mesos-marathon/pom.xml @@ -5,7 +5,8 @@ com.baeldung mesos-marathon 0.0.1-SNAPSHOT - + mesos-marathon + parent-boot-1 com.baeldung diff --git a/metrics/pom.xml b/metrics/pom.xml index 9cf1ec588f..d7d7a8a911 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -3,6 +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 metrics + metrics parent-modules @@ -65,7 +66,7 @@ org.springframework.boot spring-boot-starter-web - ${spring.boot.ver} + 2.0.7.RELEASE @@ -84,44 +85,21 @@ spectator-api ${spectator-api.version} - - - org.assertj - assertj-core - test - - + + + org.assertj + assertj-core + 3.11.1 + test + + - - - - org.springframework.boot - spring-boot-dependencies - pom - import - ${spring.boot.ver} - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone - - false - - - - 3.1.2 3.1.0 0.12.17 0.12.0.RELEASE - 2.0.0.M5 2.9.1 0.57.1 diff --git a/metrics/src/main/java/com/baeldung/metrics/micrometer/MicrometerApp.java b/metrics/src/main/java/com/baeldung/metrics/micrometer/MicrometerApp.java index cf818f6600..1d738085ce 100644 --- a/metrics/src/main/java/com/baeldung/metrics/micrometer/MicrometerApp.java +++ b/metrics/src/main/java/com/baeldung/metrics/micrometer/MicrometerApp.java @@ -1,10 +1,11 @@ package com.baeldung.metrics.micrometer; -import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; +import io.micrometer.core.instrument.binder.JvmThreadMetrics; + @SpringBootApplication public class MicrometerApp { diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 7b722306b6..aa69c77f73 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -7,15 +7,10 @@ com.baeldung.micronaut.helloworld.server.ServerApplication - 1.0.0.M2 - 9 + 1.0.0.RC2 + 1.8 - - - jcenter.bintray.com - http://jcenter.bintray.com - - + diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java index d4051cef52..96bc51f235 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java @@ -1,7 +1,7 @@ package com.baeldung.micronaut.helloworld.client; import io.micronaut.http.HttpRequest; -import io.micronaut.http.client.Client; +import io.micronaut.http.client.annotation.Client; import io.micronaut.http.client.RxHttpClient; import io.reactivex.Single; diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java index 8a691d5b06..d29a97fd50 100644 --- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java +++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java @@ -1,10 +1,7 @@ package com.baeldung.micronaut.helloworld.client; import io.micronaut.http.annotation.Get; -import io.micronaut.http.client.Client; -import io.micronaut.http.client.RxHttpClient; - -import javax.inject.Inject; +import io.micronaut.http.client.annotation.Client; @Client("/greet") public interface GreetingClient { diff --git a/microprofile/pom.xml b/microprofile/pom.xml index d75b6443ed..52df348ace 100644 --- a/microprofile/pom.xml +++ b/microprofile/pom.xml @@ -5,6 +5,7 @@ com.baeldung microprofile 1.0-SNAPSHOT + microprofile war diff --git a/msf4j/pom.xml b/msf4j/pom.xml index 9a6483772b..4a6f63159d 100644 --- a/msf4j/pom.xml +++ b/msf4j/pom.xml @@ -5,6 +5,7 @@ com.baeldung.msf4j msf4j 0.0.1-SNAPSHOT + msf4j parent-modules diff --git a/muleesb/pom.xml b/muleesb/pom.xml index b34123567a..4b74b6d4f4 100644 --- a/muleesb/pom.xml +++ b/muleesb/pom.xml @@ -6,9 +6,9 @@ com.mycompany muleesb 1.0.0-SNAPSHOT - mule - Mule muleesb Application - + muleesb + mule + com.baeldung parent-modules diff --git a/mustache/pom.xml b/mustache/pom.xml index a276dfbf43..1b89997996 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -7,10 +7,10 @@ mustache - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -30,6 +30,11 @@ log4j ${log4j.version} + + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot diff --git a/mustache/src/main/resources/application.properties b/mustache/src/main/resources/application.properties index e69de29bb2..011bbae980 100644 --- a/mustache/src/main/resources/application.properties +++ b/mustache/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.mustache.suffix:.html \ No newline at end of file diff --git a/mvn-wrapper/.gitignore b/mvn-wrapper/.gitignore deleted file mode 100644 index 2af7cefb0a..0000000000 --- a/mvn-wrapper/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/mvn-wrapper/README.md b/mvn-wrapper/README.md deleted file mode 100644 index bd299d41ed..0000000000 --- a/mvn-wrapper/README.md +++ /dev/null @@ -1,22 +0,0 @@ -Setting up the Maven Wrapper on an Application -============================================== - -This is the code that shows the configurations of maven wrapper on a SpringBoot project. - -### Requirements - -- Maven -- JDK 7 - -### Running - -To build and start the server simply type - -```bash -$ ./mvn clean install -$ ./mvn spring-boot:run -``` - -Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080) - -Enjoy it :) \ No newline at end of file diff --git a/mvn-wrapper/pom.xml b/mvn-wrapper/pom.xml deleted file mode 100644 index 7f45fe218d..0000000000 --- a/mvn-wrapper/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - 4.0.0 - mvn-wrapper - 0.0.1-SNAPSHOT - jar - mvn-wrapper - Setting up the Maven Wrapper - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-web - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java b/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java deleted file mode 100644 index 3007d24ed0..0000000000 --- a/mvn-wrapper/src/main/java/com/baeldung/MvnWrapperApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MvnWrapperApplication { - public static void main(String[] args) { - SpringApplication.run(MvnWrapperApplication.class, args); - } -} diff --git a/mybatis/pom.xml b/mybatis/pom.xml index aa9ff9e288..4e63d14ded 100644 --- a/mybatis/pom.xml +++ b/mybatis/pom.xml @@ -5,7 +5,8 @@ com.baeldung mybatis 1.0.0-SNAPSHOT - + mybatis + com.baeldung parent-modules diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml index 22abbedc8c..fbce0ea072 100644 --- a/optaplanner/pom.xml +++ b/optaplanner/pom.xml @@ -2,14 +2,15 @@ + 4.0.0 + optaplanner + optaplanner + parent-modules com.baeldung 1.0.0-SNAPSHOT - 4.0.0 - - optaplanner diff --git a/parent-boot-1/README.md b/parent-boot-1/README.md index ff12555376..8b312c348a 100644 --- a/parent-boot-1/README.md +++ b/parent-boot-1/README.md @@ -1 +1,2 @@ -## Relevant articles: + +This is a parent module for all projects using Spring Boot 1. diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml index 171806390d..53f91f975d 100644 --- a/parent-boot-1/pom.xml +++ b/parent-boot-1/pom.xml @@ -3,6 +3,7 @@ 4.0.0 parent-boot-1 0.0.1-SNAPSHOT + parent-boot-1 pom Parent for all Spring Boot 1.x modules diff --git a/parent-boot-2/README.md b/parent-boot-2/README.md index ff12555376..3f18bdf38e 100644 --- a/parent-boot-2/README.md +++ b/parent-boot-2/README.md @@ -1 +1,2 @@ -## Relevant articles: + +This is a parent module for all projects using Spring Boot 2. diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index bb89cb2729..280d226e95 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -3,6 +3,7 @@ 4.0.0 parent-boot-2 0.0.1-SNAPSHOT + parent-boot-2 pom Parent for all Spring Boot 2 modules @@ -77,7 +78,8 @@ 3.1.0 1.0.11.RELEASE - 2.1.0.RELEASE - 2.1.0.RELEASE + 2.1.1.RELEASE + + diff --git a/parent-kotlin/README.md b/parent-kotlin/README.md new file mode 100644 index 0000000000..6c17a6ac29 --- /dev/null +++ b/parent-kotlin/README.md @@ -0,0 +1,2 @@ + +Parent module for Kotlin projects. diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index f8283bd920..73c98e1a80 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -202,7 +202,7 @@ - 1.3.0 + 1.3.10 1.0.0 0.9.5 3.11.0 diff --git a/patterns/README.md b/patterns/README.md index 221cba6456..9a15cdff02 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,8 +1,3 @@ ### Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) -- [Implementing the Template Method Pattern in Java](http://www.baeldung.com/java-template-method-pattern) -- [Chain of Responsibility Design Pattern in Java](http://www.baeldung.com/chain-of-responsibility-pattern) -- [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern) -- [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern) - diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 75f7cec73a..8046d2034b 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -12,3 +12,9 @@ - [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern) - [Interpreter Design Pattern in Java](http://www.baeldung.com/java-interpreter-pattern) - [State Design Pattern in Java](https://www.baeldung.com/java-state-design-pattern) +- [The Decorator Pattern in Java](https://www.baeldung.com/java-decorator-pattern) +- [Abstract Factory Pattern in Java](https://www.baeldung.com/java-abstract-factory-pattern) +- [Implementing the Template Method Pattern in Java](http://www.baeldung.com/java-template-method-pattern) +- [Chain of Responsibility Design Pattern in Java](http://www.baeldung.com/chain-of-responsibility-pattern) +- [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern) +- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index dc2631b36e..ac201ad653 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -4,7 +4,9 @@ 4.0.0 design-patterns 1.0 - jar + design-patterns + jar + com.baeldung patterns diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java b/patterns/design-patterns/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java similarity index 100% rename from core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java rename to patterns/design-patterns/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java b/patterns/design-patterns/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java similarity index 100% rename from core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java rename to patterns/design-patterns/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java diff --git a/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java diff --git a/patterns/front-controller/pom.xml b/patterns/front-controller/pom.xml index 435b0dd9cd..bb003dd00a 100644 --- a/patterns/front-controller/pom.xml +++ b/patterns/front-controller/pom.xml @@ -3,6 +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 front-controller + front-controller war diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index fa94d5d1fd..33589dc242 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - intercepting-filter + intercepting-filter war diff --git a/patterns/pom.xml b/patterns/pom.xml index df09f1836a..bc1f5173e2 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -4,6 +4,7 @@ 4.0.0 patterns pom + patterns com.baeldung diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index 8c9d027724..7d77c2a0e3 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -4,7 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 performance-tests - + performance-tests + parent-modules com.baeldung diff --git a/persistence-modules/README.md b/persistence-modules/README.md index f12163bd6a..87dc9522fd 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -9,3 +9,5 @@ - [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) - [A Guide to Jdbi](http://www.baeldung.com/jdbi) - [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive) diff --git a/persistence-modules/hbase/pom.xml b/persistence-modules/hbase/pom.xml index ffd1464482..daf0db5291 100644 --- a/persistence-modules/hbase/pom.xml +++ b/persistence-modules/hbase/pom.xml @@ -3,6 +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 hbase + hbase parent-modules diff --git a/persistence-modules/hibernate-ogm/README.md b/persistence-modules/hibernate-ogm/README.md new file mode 100644 index 0000000000..f4a5bb6c3b --- /dev/null +++ b/persistence-modules/hibernate-ogm/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Guide to Hibernate OGM](http://www.baeldung.com/xxxx) + diff --git a/persistence-modules/hibernate-ogm/pom.xml b/persistence-modules/hibernate-ogm/pom.xml new file mode 100644 index 0000000000..2ccac03bd3 --- /dev/null +++ b/persistence-modules/hibernate-ogm/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + com.baeldung + hibernate-ogm + 0.0.1-SNAPSHOT + hibernate-ogm + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + org.hibernate.ogm + hibernate-ogm-mongodb + 5.4.0.Final + + + + org.hibernate.ogm + hibernate-ogm-neo4j + 5.4.0.Final + + + + org.jboss.narayana.jta + narayana-jta + 5.5.23.Final + + + + junit + junit + 4.12 + test + + + org.easytesting + fest-assert + 1.4 + test + + + + + hibernate-ogm + + + src/main/resources + true + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java new file mode 100644 index 0000000000..29f01ecde7 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java @@ -0,0 +1,54 @@ +package com.baeldung.hibernate.ogm; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Article { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String articleId; + + private String articleTitle; + + @ManyToOne + private Author author; + + // constructors, getters and setters... + + Article() { + } + + public Article(String articleTitle) { + this.articleTitle = articleTitle; + } + + public String getArticleId() { + return articleId; + } + + public void setArticleId(String articleId) { + this.articleId = articleId; + } + + public String getArticleTitle() { + return articleTitle; + } + + public void setArticleTitle(String articleTitle) { + this.articleTitle = articleTitle; + } + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java new file mode 100644 index 0000000000..9e60c9f934 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Author { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String authorId; + + private String authorName; + + @ManyToOne + private Editor editor; + + @OneToMany(mappedBy = "author", cascade = CascadeType.PERSIST) + private Set
authoredArticles = new HashSet<>(); + + // constructors, getters and setters... + + Author() { + } + + public Author(String authorName) { + this.authorName = authorName; + } + + public String getAuthorId() { + return authorId; + } + + public void setAuthorId(String authorId) { + this.authorId = authorId; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public Editor getEditor() { + return editor; + } + + public void setEditor(Editor editor) { + this.editor = editor; + } + + public Set
getAuthoredArticles() { + return authoredArticles; + } + + public void setAuthoredArticles(Set
authoredArticles) { + this.authoredArticles = authoredArticles; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java new file mode 100644 index 0000000000..2c3f720e91 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Editor { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String editorId; + + private String editorName; + + @OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST) + private Set assignedAuthors = new HashSet<>(); + + // constructors, getters and setters... + + Editor() { + } + + public Editor(String editorName) { + this.editorName = editorName; + } + + public String getEditorId() { + return editorId; + } + + public void setEditorId(String editorId) { + this.editorId = editorId; + } + + public String getEditorName() { + return editorName; + } + + public void setEditorName(String editorName) { + this.editorName = editorName; + } + + public Set getAssignedAuthors() { + return assignedAuthors; + } + + public void setAssignedAuthors(Set assignedAuthors) { + this.assignedAuthors = assignedAuthors; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..43c86fb55b --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,24 @@ + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java new file mode 100644 index 0000000000..d7fd49d917 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.hibernate.ogm; + +import static org.fest.assertions.Assertions.assertThat; + +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.transaction.TransactionManager; + +import org.junit.Test; + +public class EditorUnitTest { + /* + @Test + public void givenMongoDB_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + */ + @Test + public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + + private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.persist(editor); + entityManager.close(); + transactionManager.commit(); + } + + private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId()); + assertThat(loadedEditor).isNotNull(); + assertThat(loadedEditor.getEditorName()).isEqualTo("Tom"); + assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName") + .containsOnly("Maria", "Mike"); + Map loadedAuthors = loadedEditor.getAssignedAuthors() + .stream() + .collect(Collectors.toMap(Author::getAuthorName, e -> e)); + assertThat(loadedAuthors.get("Maria") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Basic of Hibernate OGM"); + assertThat(loadedAuthors.get("Mike") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM"); + entityManager.close(); + transactionManager.commit(); + } + + private Editor generateTestData() { + Editor tom = new Editor("Tom"); + Author maria = new Author("Maria"); + Author mike = new Author("Mike"); + Article basic = new Article("Basic of Hibernate OGM"); + Article intermediate = new Article("Intermediate of Hibernate OGM"); + Article advanced = new Article("Advanced of Hibernate OGM"); + maria.getAuthoredArticles() + .add(basic); + basic.setAuthor(maria); + mike.getAuthoredArticles() + .add(intermediate); + intermediate.setAuthor(mike); + mike.getAuthoredArticles() + .add(advanced); + advanced.setAuthor(mike); + tom.getAssignedAuthors() + .add(maria); + maria.setEditor(tom); + tom.getAssignedAuthors() + .add(mike); + mike.setEditor(tom); + return tom; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index a94379b5cb..2b948a683a 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -19,3 +19,7 @@ - [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](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) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 24f4055a82..af94025a73 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -1,10 +1,12 @@ - + 4.0.0 com.baeldung hibernate5 0.0.1-SNAPSHOT + hibernate5 com.baeldung @@ -35,6 +37,11 @@ hibernate-spatial ${hibernate.version} + + org.hibernate + hibernate-c3p0 + ${hibernate.version} + mysql mysql-connector-java @@ -50,6 +57,22 @@ hibernate-testing 5.2.2.Final + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + net.bytebuddy + byte-buddy + 1.9.5 + + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + @@ -63,11 +86,12 @@ - 5.3.6.Final + 5.3.7.Final 6.0.6 2.2.3 1.4.196 3.8.0 + 2.9.7 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java new file mode 100644 index 0000000000..35cfe55ba6 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.criteriaquery; + +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() { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(); + } + return sessionFactory; + } + + private static SessionFactory buildSessionFactory() { + try { + ServiceRegistry serviceRegistry = configureServiceRegistry(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + + metadataSources.addAnnotatedClass(Student.class); + 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/criteriaquery/Student.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java new file mode 100644 index 0000000000..314e7ca557 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.criteriaquery; + +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 = "students") +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @Column(name = "grad_year") + private int gradYear; + + public int getId() { + return id; + } + + public void setId(int 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 int getGradYear() { + return gradYear; + } + + public void setGradYear(int gradYear) { + this.gradYear = gradYear; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java index 8b5d9c41f3..6510e70650 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java @@ -1,7 +1,17 @@ package com.baeldung.hibernate.entities; -import javax.persistence.*; +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 @@ -16,7 +26,7 @@ public class DeptEmployee { @ManyToOne private Department department; - + public DeptEmployee(String name, String employeeNumber, Department department) { this.name = name; this.employeeNumber = employeeNumber; diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java new file mode 100644 index 0000000000..cc0c234df0 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/findall/FindAll.java @@ -0,0 +1,35 @@ +package com.baeldung.hibernate.findall; + +import java.util.List; + +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import org.hibernate.Session; + +import com.baeldung.hibernate.pojo.Student; + +public class FindAll { + + private Session session; + + public FindAll(Session session) { + super(); + this.session = session; + } + + public List findAllWithJpql() { + return session.createQuery("SELECT a FROM Student a", Student.class).getResultList(); + } + + public List findAllWithCriteriaQuery() { + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Student.class); + Root rootEntry = cq.from(Student.class); + CriteriaQuery all = cq.select(rootEntry); + TypedQuery allQuery = session.createQuery(all); + return allQuery.getResultList(); + } +} 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 new file mode 100644 index 0000000000..972ade9671 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java @@ -0,0 +1,66 @@ +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) { + if (sessionFactory == null) { + sessionFactory = buildSessionFactory(strategy); + } + return sessionFactory; + } + + 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/onetoone/Strategy.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java new file mode 100644 index 0000000000..3180566ca5 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/Strategy.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.onetoone; + + +import java.util.Arrays; +import java.util.List; + +public enum Strategy { + //See that the classes belongs to different packages + FOREIGN_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.foreignkeybased.User.class, + com.baeldung.hibernate.onetoone.foreignkeybased.Address.class)), + SHARED_PRIMARY_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.sharedkeybased.User.class, + com.baeldung.hibernate.onetoone.sharedkeybased.Address.class)), + JOIN_TABLE_BASED(Arrays.asList(com.baeldung.hibernate.onetoone.jointablebased.Employee.class, + com.baeldung.hibernate.onetoone.jointablebased.WorkStation.class)); + + private List> entityClasses; + + Strategy(List> entityClasses) { + this.entityClasses = entityClasses; + } + + public List> getEntityClasses() { + return entityClasses; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java new file mode 100644 index 0000000000..e05eb46030 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.onetoone.foreignkeybased; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "address") +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "street") + private String street; + + @Column(name = "city") + private String city; + + @OneToOne(mappedBy = "address") + private User user; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java new file mode 100644 index 0000000000..dda972f29c --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java @@ -0,0 +1,51 @@ +package com.baeldung.hibernate.onetoone.foreignkeybased; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "username") + private String userName; + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "address_id", referencedColumnName = "id") + private Address address; + + 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 Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java new file mode 100644 index 0000000000..a0bc101b9f --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.onetoone.jointablebased; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "employee") +public class Employee { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "ename") + private String name; + + @OneToOne(cascade = CascadeType.ALL) + @JoinTable(name = "emp_workstation", joinColumns = {@JoinColumn(name = "employee_id", referencedColumnName = "id")}, + inverseJoinColumns = {@JoinColumn(name = "workstation_id", referencedColumnName = "id")}) + private WorkStation workStation; + + 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 WorkStation getWorkStation() { + return workStation; + } + + public void setWorkStation(WorkStation workStation) { + this.workStation = workStation; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java new file mode 100644 index 0000000000..f530611f6e --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java @@ -0,0 +1,61 @@ +package com.baeldung.hibernate.onetoone.jointablebased; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "workstation") +public class WorkStation { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "workstation_number") + private Integer workstationNumber; + + @Column(name = "floor") + private String floor; + + @OneToOne(mappedBy = "workStation") + private Employee employee; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getWorkstationNumber() { + return workstationNumber; + } + + public void setWorkstationNumber(Integer workstationNumber) { + this.workstationNumber = workstationNumber; + } + + public String getFloor() { + return floor; + } + + public void setFloor(String floor) { + this.floor = floor; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java new file mode 100644 index 0000000000..927516f6bb --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.onetoone.sharedkeybased; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.MapsId; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "address") +public class Address { + + @Id + @Column(name = "id") + private Long id; + + @Column(name = "street") + private String street; + + @Column(name = "city") + private String city; + + @OneToOne + @MapsId + private User user; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java new file mode 100644 index 0000000000..fa00db1271 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.onetoone.sharedkeybased; + + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "username") + private String userName; + + @OneToOne(mappedBy = "user", cascade = CascadeType.ALL) + private Address address; + + 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 Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java new file mode 100644 index 0000000000..d45daabe71 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/operations/HibernateOperations.java @@ -0,0 +1,114 @@ +package com.baeldung.hibernate.operations; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import com.baeldung.hibernate.pojo.Movie; + +/** + * + *Class to illustrate the usage of EntityManager API. + */ +public class HibernateOperations { + + private static final EntityManagerFactory emf; + + /** + * Static block for creating EntityManagerFactory. The Persistence class looks for META-INF/persistence.xml in the classpath. + */ + static { + emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog"); + } + + /** + * Static method returning EntityManager. + * @return EntityManager + */ + public static EntityManager getEntityManager() { + return emf.createEntityManager(); + } + + /** + * Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves. + */ + public void saveMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = new Movie(); + movie.setId(1L); + movie.setMovieName("The Godfather"); + movie.setReleaseYear(1972); + movie.setLanguage("English"); + em.persist(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a single object. + * @return Movie + */ + public Movie queryForMovieById() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1") + .setParameter(1, new Long(1L)) + .getSingleResult(); + return movie; + } + + /** + * Method to illustrate the querying support in EntityManager when the result is a list. + * @return + */ + public List queryForMovies() { + EntityManager em = HibernateOperations.getEntityManager(); + List movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1") + .setParameter(1, "English") + .getResultList(); + return movies; + } + + /** + * Method to illustrate the usage of find() method. + * @param movieId + * @return Movie + */ + public Movie getMovie(Long movieId) { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = em.find(Movie.class, new Long(movieId)); + return movie; + } + + /** + * Method to illustrate the usage of merge() function. + */ + public void mergeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + Movie movie = getMovie(1L); + em.detach(movie); + movie.setLanguage("Italian"); + em.getTransaction() + .begin(); + em.merge(movie); + em.getTransaction() + .commit(); + } + + /** + * Method to illustrate the usage of remove() function. + */ + public void removeMovie() { + EntityManager em = HibernateOperations.getEntityManager(); + em.getTransaction() + .begin(); + Movie movie = em.find(Movie.class, new Long(1L)); + em.remove(movie); + em.getTransaction() + .commit(); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java new file mode 100644 index 0000000000..6bd1c24869 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Entity +@Table(name = "Customers") +public class Customer { + + @Id + private int id; + + private String firstName; + + private String lastName; + + private String customerAttributeJSON; + + @Convert(converter = HashMapConverter.class) + private Map customerAttributes; + + public int getId() { + return id; + } + + public void setId(int 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 getCustomerAttributeJSON() { + return customerAttributeJSON; + } + + public void setCustomerAttributeJSON(String customerAttributeJSON) { + this.customerAttributeJSON = customerAttributeJSON; + } + + public Map getCustomerAttributes() { + return customerAttributes; + } + + public void setCustomerAttributes(Map customerAttributes) { + this.customerAttributes = customerAttributes; + } + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public void serializeCustomerAttributes() throws JsonProcessingException { + this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes); + } + + public void deserializeCustomerAttributes() throws IOException { + this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java new file mode 100644 index 0000000000..b1c2d50480 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.AttributeConverter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.interceptors.CustomInterceptor; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HashMapConverter implements AttributeConverter, String> { + + private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public String convertToDatabaseColumn(Map customerInfo) { + + String customerInfoJson = null; + try { + customerInfoJson = objectMapper.writeValueAsString(customerInfo); + } catch (final JsonProcessingException e) { + logger.error("JSON writing error", e); + } + + return customerInfoJson; + } + + @Override + public Map convertToEntityAttribute(String customerInfoJSON) { + + Map customerInfo = null; + try { + customerInfo = objectMapper.readValue(customerInfoJSON, Map.class); + } catch (final IOException e) { + logger.error("JSON reading error", e); + } + + return customerInfo; + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Movie.java new file mode 100644 index 0000000000..5fae7f6a97 --- /dev/null +++ b/persistence-modules/hibernate5/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/resources/META-INF/persistence.xml b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..4dfade1af3 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,19 @@ + + + + Hibernate EntityManager Demo + com.baeldung.hibernate.pojo.Movie + true + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/resources/init_database.sql b/persistence-modules/hibernate5/src/main/resources/init_database.sql new file mode 100644 index 0000000000..b2848aa256 --- /dev/null +++ b/persistence-modules/hibernate5/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/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java new file mode 100644 index 0000000000..cb73fe348c --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java @@ -0,0 +1,98 @@ +package com.baeldung.hibernate; + +import com.baeldung.hibernate.entities.Department; +import com.baeldung.hibernate.entities.DeptEmployee; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.query.NativeQuery; +import org.hibernate.query.Query; +import org.junit.*; + +import java.io.IOException; + +public class NamedQueryIntegrationTest { + private static Session session; + + private Transaction transaction; + + private Long purchaseDeptId; + + @BeforeClass + public static void setUpClass() throws IOException { + session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession(); + } + + @Before + public void setUp() throws IOException { + transaction = session.beginTransaction(); + session.createNativeQuery("delete from deptemployee").executeUpdate(); + session.createNativeQuery("delete from department").executeUpdate(); + Department salesDepartment = new Department("Sales"); + Department purchaseDepartment = new Department("Purchase"); + DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment); + DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment); + DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment); + session.persist(salesDepartment); + session.persist(purchaseDepartment); + purchaseDeptId = purchaseDepartment.getId(); + session.persist(employee1); + session.persist(employee2); + session.persist(employee3); + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + if(transaction.isActive()) { + transaction.rollback(); + } + } + + @Test + public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() { + Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class); + query.setParameter("employeeNo", "001"); + DeptEmployee result = query.getSingleResult(); + Assert.assertNotNull(result); + Assert.assertEquals("John Wayne", result.getName()); + } + + @Test + public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() { + Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class); + query.setParameter("name", "John Wayne"); + DeptEmployee result = query.getSingleResult(); + Assert.assertNotNull(result); + Assert.assertEquals("001", result.getEmployeeNumber()); + } + + @Test + public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() { + @SuppressWarnings("rawtypes") + NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName"); + query.setParameter("name", "John Wayne"); + DeptEmployee result = (DeptEmployee) query.getSingleResult(); + Assert.assertNotNull(result); + Assert.assertEquals("001", result.getEmployeeNumber()); + } + + @Test + public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() { + Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment"); + spQuery.setParameter("employeeNo", "001"); + Department newDepartment = session.find(Department.class, purchaseDeptId); + spQuery.setParameter("newDepartment", newDepartment); + spQuery.executeUpdate(); + transaction.commit(); + } + + @Test + public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() { + Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation"); + spQuery.setParameter("employeeNumber", "002"); + spQuery.setParameter("newDesignation", "Supervisor"); + spQuery.executeUpdate(); + transaction.commit(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java new file mode 100644 index 0000000000..19988b45be --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/bootstrap/BootstrapAPIIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.bootstrap; + +import com.baeldung.hibernate.pojo.Movie; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.BootstrapServiceRegistry; +import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +public class BootstrapAPIIntegrationTest { + + SessionFactory sessionFactory = null; + + @Test + public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException { + + BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder() + .build(); + + ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry) + // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient. + //.configure() + .build(); + + MetadataSources metadataSources = new MetadataSources(standardRegistry); + metadataSources.addAnnotatedClass(Movie.class); + + Metadata metadata = metadataSources.getMetadataBuilder().build(); + + sessionFactory = metadata.buildSessionFactory(); + assertNotNull(sessionFactory); + sessionFactory.close(); + } + + @After + public void clean() throws IOException { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java new file mode 100644 index 0000000000..9d368fa27e --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate.criteriaquery; + +import com.baeldung.hibernate.criteriaquery.HibernateUtil; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.query.Query; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +public class TypeSafeCriteriaIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() throws IOException { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() { + + prepareData(); + CriteriaBuilder cb = session.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = cb.createQuery(Student.class); + + Root root = criteriaQuery.from(Student.class); + criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965)); + + Query query = session.createQuery(criteriaQuery); + List results = query.getResultList(); + + assertNotNull(results); + assertEquals(1, results.size()); + + Student student = results.get(0); + + assertEquals("Ken", student.getFirstName()); + assertEquals("Thompson", student.getLastName()); + assertEquals(1965, student.getGradYear()); + } + + private void prepareData() { + Student student1 = new Student(); + student1.setFirstName("Ken"); + student1.setLastName("Thompson"); + student1.setGradYear(1965); + + session.save(student1); + + Student student2 = new Student(); + student2.setFirstName("Dennis"); + student2.setLastName("Ritchie"); + student2.setGradYear(1963); + + session.save(student2); + session.getTransaction().commit(); + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java new file mode 100644 index 0000000000..8a1b9e9791 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.hibernate.findall; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Student; + +public class FindAllUnitTest { + + private Session session; + private Transaction transaction; + + private FindAll findAll; + + @Before + public void setUp() throws IOException { + + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + findAll = new FindAll(session); + + session.createNativeQuery("delete from Student").executeUpdate(); + + Student student1 = new Student(); + session.persist(student1); + + Student student2 = new Student(); + session.persist(student2); + + Student student3 = new Student(); + session.persist(student3); + + transaction.commit(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenCriteriaQuery_WhenFindAll_ThenGetAllPersons() { + List list = findAll.findAllWithCriteriaQuery(); + assertEquals(3, list.size()); + } + + @Test + public void givenJpql_WhenFindAll_ThenGetAllPersons() { + List list = findAll.findAllWithJpql(); + assertEquals(3, list.size()); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java new file mode 100644 index 0000000000..475c93f6ff --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationFKBasedIntegrationTest.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.onetoone; + +import com.baeldung.hibernate.onetoone.foreignkeybased.Address; +import com.baeldung.hibernate.onetoone.foreignkeybased.User; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class HibernateOneToOneAnnotationFKBasedIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(Strategy.FOREIGN_KEY); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreates1to1relationship() { + User user = new User(); + user.setUserName("alice@baeldung.com"); + + Address address = new Address(); + address.setStreet("FK Street"); + address.setCity("FK City"); + + address.setUser(user); + user.setAddress(address); + + //Address entry will automatically be created by hibernate, since cascade type is specified as ALL + session.persist(user); + session.getTransaction().commit(); + + assert1to1InsertedData(); + } + + private void assert1to1InsertedData() { + @SuppressWarnings("unchecked") + List userList = session.createQuery("FROM User").list(); + + assertNotNull(userList); + assertEquals(1, userList.size()); + + User user = userList.get(0); + assertEquals("alice@baeldung.com", user.getUserName()); + + Address address = user.getAddress(); + assertNotNull(address); + assertEquals("FK Street", address.getStreet()); + assertEquals("FK City", address.getCity()); + + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java new file mode 100644 index 0000000000..df4cd4d137 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationJTBasedIntegrationTest.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.onetoone; + +import com.baeldung.hibernate.onetoone.jointablebased.Employee; +import com.baeldung.hibernate.onetoone.jointablebased.WorkStation; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class HibernateOneToOneAnnotationJTBasedIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(Strategy.JOIN_TABLE_BASED); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreates1to1relationship() { + Employee employee = new Employee(); + employee.setName("bob@baeldung.com"); + + WorkStation workStation = new WorkStation(); + workStation.setWorkstationNumber(626); + workStation.setFloor("Sixth Floor"); + + + employee.setWorkStation(workStation); + workStation.setEmployee(employee); + + session.persist(employee); + session.getTransaction().commit(); + + assert1to1InsertedData(); + } + + private void assert1to1InsertedData() { + @SuppressWarnings("unchecked") + List employeeList = session.createQuery("FROM Employee").list(); + assertNotNull(employeeList); + assertEquals(1, employeeList.size()); + + Employee employee = employeeList.get(0); + assertEquals("bob@baeldung.com", employee.getName()); + + WorkStation workStation = employee.getWorkStation(); + + assertNotNull(workStation); + assertEquals((long) 626, (long) workStation.getWorkstationNumber()); + assertEquals("Sixth Floor", workStation.getFloor()); + + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java new file mode 100644 index 0000000000..7931a8e3fe --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/onetoone/HibernateOneToOneAnnotationSPKBasedIntegrationTest.java @@ -0,0 +1,79 @@ +package com.baeldung.hibernate.onetoone; + +import com.baeldung.hibernate.onetoone.sharedkeybased.Address; +import com.baeldung.hibernate.onetoone.sharedkeybased.User; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class HibernateOneToOneAnnotationSPKBasedIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(Strategy.SHARED_PRIMARY_KEY); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenData_whenInsert_thenCreates1to1relationship() { + User user = new User(); + user.setUserName("alice@baeldung.com"); + + Address address = new Address(); + address.setStreet("SPK Street"); + address.setCity("SPK City"); + + address.setUser(user); + user.setAddress(address); + + //Address entry will automatically be created by hibernate, since cascade type is specified as ALL + session.persist(user); + session.getTransaction().commit(); + + assert1to1InsertedData(); + } + + + private void assert1to1InsertedData() { + @SuppressWarnings("unchecked") + List userList = session.createQuery("FROM User").list(); + assertNotNull(userList); + assertEquals(1, userList.size()); + + User user = userList.get(0); + assertEquals("alice@baeldung.com", user.getUserName()); + + Address address = user.getAddress(); + assertNotNull(address); + assertEquals("SPK Street", address.getStreet()); + assertEquals("SPK City", address.getCity()); + } + + @After + public void tearDown() { + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java new file mode 100644 index 0000000000..ecbb073e89 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.hibernate.persistjson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class PersistJSONUnitTest { + + private Session session; + + @Before + public void init() { + try { + Configuration configuration = new Configuration(); + + Properties properties = new Properties(); + properties.load(Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("hibernate-persistjson.properties")); + + configuration.setProperties(properties); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Customer.class); + + SessionFactory factory = metadataSources.buildMetadata() + .buildSessionFactory(); + + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close() { + if (session != null) + session.close(); + } + + @Test + public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + customer.serializeCustomerAttributes(); + + String serialized = customer.getCustomerAttributeJSON(); + + customer.setCustomerAttributeJSON(serialized); + customer.deserializeCustomerAttributes(); + + Map deserialized = customer.getCustomerAttributes(); + + assertEquals("123 Main Street", deserialized.get("address")); + } + + @Test + public void givenCustomer_whenSaving_thenAttributesAreConverted() { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + session.beginTransaction(); + + int id = (int) session.save(customer); + + session.flush(); + session.clear(); + + Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(2, result.getCustomerAttributes() + .size()); + } + +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-namedquery.properties new file mode 100644 index 0000000000..457f965347 --- /dev/null +++ b/persistence-modules/hibernate5/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/hibernate5/src/test/resources/hibernate-persistjson.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties new file mode 100644 index 0000000000..2cf8ac5b63 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties @@ -0,0 +1,7 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +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/hibernate5/src/test/resources/hibernate.properties b/persistence-modules/hibernate5/src/test/resources/hibernate.properties index 7b8764637b..c14782ce0f 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate.properties @@ -6,4 +6,9 @@ jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file +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/mvn-wrapper/src/main/resources/application.properties b/persistence-modules/hibernate5/transaction.log similarity index 100% rename from mvn-wrapper/src/main/resources/application.properties rename to persistence-modules/hibernate5/transaction.log diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 36ec6b5ac8..aac5d49547 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -4,6 +4,7 @@ com.baeldung java-cassandra 1.0.0-SNAPSHOT + java-cassandra com.baeldung diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index 870707c750..2738ef85ff 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -5,6 +5,7 @@ com.baeldung java-cockroachdb 1.0-SNAPSHOT + java-cockroachdb parent-modules @@ -21,15 +22,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 42.1.4 diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 3bab6faa29..7d843af9ea 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) diff --git a/persistence-modules/java-jdbi/pom.xml b/persistence-modules/java-jdbi/pom.xml index 885906fcd0..dfb31b26e8 100644 --- a/persistence-modules/java-jdbi/pom.xml +++ b/persistence-modules/java-jdbi/pom.xml @@ -4,6 +4,7 @@ 4.0.0 java-jdbi 1.0-SNAPSHOT + java-jdbi parent-modules @@ -26,15 +27,6 @@ - - - Central - Central - http://repo1.maven.org/maven2/ - default - - - 3.1.0 2.4.0 diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 418e0a67e2..9a90216519 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -1,4 +1,5 @@ # Relevant Articles - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) -- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) \ No newline at end of file +- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) +- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index 78764f7148..ddab51a2e2 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -2,15 +2,16 @@ + 4.0.0 + java-jpa + java-jpa + parent-modules com.baeldung 1.0.0-SNAPSHOT ../../pom.xml - 4.0.0 - - java-jpa diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/MainApp.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/MainApp.java new file mode 100644 index 0000000000..88aa4389e9 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/MainApp.java @@ -0,0 +1,26 @@ +package com.baeldung.jpa.entitygraph; + +import com.baeldung.jpa.entitygraph.model.Post; +import com.baeldung.jpa.entitygraph.repo.PostRepository; + +public class MainApp { + + public static void main(String... args) { + Long postId = 1L; + Post post = null; + PostRepository postRepository = new PostRepository(); + + //Using EntityManager.find(). + post = postRepository.find(postId); + post = postRepository.findWithEntityGraph(postId); + post = postRepository.findWithEntityGraph2(postId); + + //Using JPQL: Query and TypedQuery + post = postRepository.findUsingJpql(postId); + + //Using Criteria API + post = postRepository.findUsingCriteria(postId); + + postRepository.clean(); + } +} \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java new file mode 100644 index 0000000000..40ecd3262b --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java @@ -0,0 +1,63 @@ +package com.baeldung.jpa.entitygraph.model; + +import javax.persistence.*; + +@Entity +public class Comment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String reply; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn + private Post post; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn + private User user; + //... + + public Comment() { + } + + public Comment(String reply, Post post, User user) { + this.reply = reply; + this.post = post; + this.user = user; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getReply() { + return reply; + } + + public void setReply(String reply) { + this.reply = reply; + } + + public Post getPost() { + return post; + } + + public void setPost(Post post) { + this.post = post; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java new file mode 100644 index 0000000000..59f17ae0c5 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java @@ -0,0 +1,86 @@ +package com.baeldung.jpa.entitygraph.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +@NamedEntityGraph( + name = "post-entity-graph", + attributeNodes = { + @NamedAttributeNode("subject"), + @NamedAttributeNode("user"), + @NamedAttributeNode("comments"), + } +) +@NamedEntityGraph( + name = "post-entity-graph-with-comment-users", + attributeNodes = { + @NamedAttributeNode("subject"), + @NamedAttributeNode("user"), + @NamedAttributeNode(value = "comments", subgraph = "comments-subgraph"), + }, + subgraphs = { + @NamedSubgraph( + name = "comments-subgraph", + attributeNodes = { + @NamedAttributeNode("user") + } + ) + } +) +@Entity +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String subject; + @OneToMany(mappedBy = "post") + private List comments = new ArrayList<>(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn + private User user; + //... + + public Post() { + } + + public Post(String subject, User user) { + this.subject = subject; + this.user = user; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java new file mode 100644 index 0000000000..b712100d4e --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java @@ -0,0 +1,48 @@ +package com.baeldung.jpa.entitygraph.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.IDENTITY) + private Long id; + private String name; + private String email; + + //... + + public User() { + } + + public User(String email) { + this.email = email; + } + + 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 getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java new file mode 100644 index 0000000000..28f1e1b93c --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java @@ -0,0 +1,93 @@ +package com.baeldung.jpa.entitygraph.repo; + +import com.baeldung.jpa.entitygraph.model.Post; + +import javax.persistence.*; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import java.util.HashMap; +import java.util.Map; + +public class PostRepository { + private EntityManagerFactory emf = null; + + + public PostRepository() { + Map properties = new HashMap(); + properties.put("hibernate.show_sql", "true"); + properties.put("hibernate.format_sql", "true"); + emf = Persistence.createEntityManagerFactory("entity-graph-pu", properties); + } + + public Post find(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + Post post = entityManager.find(Post.class, id); + + entityManager.close(); + return post; + } + + public Post findWithEntityGraph(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph"); + Map properties = new HashMap<>(); + properties.put("javax.persistence.fetchgraph", entityGraph); + Post post = entityManager.find(Post.class, id, properties); + + entityManager.close(); + return post; + } + + public Post findWithEntityGraph2(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.createEntityGraph(Post.class); + entityGraph.addAttributeNodes("subject"); + entityGraph.addAttributeNodes("user"); + entityGraph.addSubgraph("comments") + .addAttributeNodes("user"); + + Map properties = new HashMap<>(); + properties.put("javax.persistence.fetchgraph", entityGraph); + Post post = entityManager.find(Post.class, id, properties); + + entityManager.close(); + return post; + } + + public Post findUsingJpql(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); + Post post = entityManager.createQuery("Select p from Post p where p.id=:id", Post.class) + .setParameter("id", id) + .setHint("javax.persistence.fetchgraph", entityGraph) + .getSingleResult(); + + entityManager.close(); + return post; + } + + public Post findUsingCriteria(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Post.class); + Root root = criteriaQuery.from(Post.class); + criteriaQuery.where(criteriaBuilder.equal(root.get("id"), id)); + TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); + typedQuery.setHint("javax.persistence.loadgraph", entityGraph); + Post post = typedQuery.getSingleResult(); + + entityManager.close(); + return post; + } + + public void clean() { + emf.close(); + } +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java index 6f1e2ee5ca..2cb5679d4d 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java @@ -1,13 +1,12 @@ package com.baeldung.jpa.stringcast; -import com.sun.istack.internal.Nullable; - -import javax.persistence.EntityManager; -import javax.persistence.Query; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.persistence.Query; + public class QueryExecutor { public static List executeNativeQueryNoCastCheck(String statement, EntityManager em) { @@ -24,10 +23,7 @@ public class QueryExecutor { } if (results.get(0) instanceof String) { - return ((List) results) - .stream() - .map(s -> new String[] { s }) - .collect(Collectors.toList()); + return ((List) results).stream().map(s -> new String[] { s }).collect(Collectors.toList()); } else { return (List) results; } diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 3fdc8ce27c..433d456cc9 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -9,12 +9,12 @@ org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.sqlresultsetmapping.ScheduledDay - + - - - + value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/> + + + @@ -25,28 +25,45 @@ org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.jpa.stringcast.Message - - - - - - + + + + + + - + org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.jpa.model.Car - - - - - - + + + + + + - + + + com.baeldung.jpa.entitygraph.model.Post + com.baeldung.jpa.entitygraph.model.User + com.baeldung.jpa.entitygraph.model.Comment + true + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/resources/data-init.sql b/persistence-modules/java-jpa/src/main/resources/data-init.sql new file mode 100644 index 0000000000..86c3f2a651 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/resources/data-init.sql @@ -0,0 +1,8 @@ +INSERT INTO `USER` (`ID`,`NAME`,`EMAIL`) VALUES (1,'user1','user1@test.com'); +INSERT INTO `USER` (`ID`,`NAME`,`EMAIL`) VALUES (2,'user2','user2@test.com'); +INSERT INTO `USER` (`ID`,`NAME`,`EMAIL`) VALUES (3,'user3','user3@test.com'); + +INSERT INTO `POST` (`ID`,`SUBJECT`,`USER_ID`) VALUES (1,'JPA Entity Graph In Action',1); + +INSERT INTO `COMMENT` (`ID`,`REPLY`,`POST_ID`,`USER_ID`) VALUES (1,'Nice !!',1,2); +INSERT INTO `COMMENT` (`ID`,`REPLY`,`POST_ID`,`USER_ID`) VALUES (2,'Cool !!',1,3); diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entitygraph/repo/PostRepositoryIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entitygraph/repo/PostRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4724bb41ad --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entitygraph/repo/PostRepositoryIntegrationTest.java @@ -0,0 +1,68 @@ +package com.baeldung.jpa.entitygraph.repo; + +import com.baeldung.jpa.entitygraph.model.Comment; +import com.baeldung.jpa.entitygraph.model.Post; +import com.baeldung.jpa.entitygraph.model.User; +import org.hibernate.LazyInitializationException; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class PostRepositoryIntegrationTest { + + private static PostRepository postRepository = null; + + @BeforeClass + public static void once() { + postRepository = new PostRepository(); + } + + @Test(expected = LazyInitializationException.class) + public void find() { + Post post = postRepository.find(1L); + assertNotNull(post.getUser()); + String email = post.getUser().getEmail(); + assertNull(email); + } + + @Test + public void findWithEntityGraph() { + Post post = postRepository.findWithEntityGraph(1L); + assertNotNull(post.getUser()); + String email = post.getUser().getEmail(); + assertNotNull(email); + } + + @Test(expected = LazyInitializationException.class) + public void findWithEntityGraph_Comment_Without_User() { + Post post = postRepository.findWithEntityGraph(1L); + assertNotNull(post.getUser()); + String email = post.getUser().getEmail(); + assertNotNull(email); + assertNotNull(post.getComments()); + assertEquals(post.getComments().size(), 2); + Comment comment = post.getComments().get(0); + assertNotNull(comment); + User user = comment.getUser(); + user.getEmail(); + } + + @Test + public void findWithEntityGraph2_Comment_With_User() { + Post post = postRepository.findWithEntityGraph2(1L); + assertNotNull(post.getComments()); + assertEquals(post.getComments().size(), 2); + Comment comment = post.getComments().get(0); + assertNotNull(comment); + User user = comment.getUser(); + assertNotNull(user); + assertEquals(user.getEmail(), "user2@test.com"); + } + + @AfterClass + public static void destroy() { + postRepository.clean(); + } +} diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index bbc48f54c2..9658ef567f 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -5,6 +5,7 @@ com.baeldung java-mongodb 1.0-SNAPSHOT + java-mongodb com.baeldung diff --git a/persistence-modules/jnosql/jnosql-artemis/pom.xml b/persistence-modules/jnosql/jnosql-artemis/pom.xml index 9c2bfd1ba0..8a978fb179 100644 --- a/persistence-modules/jnosql/jnosql-artemis/pom.xml +++ b/persistence-modules/jnosql/jnosql-artemis/pom.xml @@ -3,6 +3,9 @@ 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 + jnosql-artemis + jnosql-artemis + war com.baeldung.jnosql @@ -10,9 +13,6 @@ 1.0-SNAPSHOT - jnosql-artemis - war - 2.4.2 false diff --git a/persistence-modules/jnosql/jnosql-diana/pom.xml b/persistence-modules/jnosql/jnosql-diana/pom.xml index 767defb2a8..126f0314d9 100644 --- a/persistence-modules/jnosql/jnosql-diana/pom.xml +++ b/persistence-modules/jnosql/jnosql-diana/pom.xml @@ -3,15 +3,15 @@ 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 - + jnosql-diana + jnosql-diana + com.baeldung.jnosql jnosql 1.0-SNAPSHOT - jnosql-diana - diff --git a/persistence-modules/jnosql/pom.xml b/persistence-modules/jnosql/pom.xml index c87ad3cf4b..5fb29a3b9c 100644 --- a/persistence-modules/jnosql/pom.xml +++ b/persistence-modules/jnosql/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 - com.baeldung.jnosql jnosql 1.0-SNAPSHOT + jnosql pom diff --git a/persistence-modules/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml index cb2bee8d48..b06d38e6a0 100644 --- a/persistence-modules/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -3,6 +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 liquibase + liquibase parent-modules diff --git a/persistence-modules/orientdb/pom.xml b/persistence-modules/orientdb/pom.xml index e4bc9a0585..a8ac3fb789 100644 --- a/persistence-modules/orientdb/pom.xml +++ b/persistence-modules/orientdb/pom.xml @@ -4,8 +4,8 @@ 4.0.0 orientdb 0.0.1-SNAPSHOT + orientdb jar - intro-orientdb introduction to the OrientDB Java APIs diff --git a/persistence-modules/redis/README.md b/persistence-modules/redis/README.md index dd655ca7aa..21cd048693 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -1,5 +1,4 @@ ### Relevant Articles: - [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) -- [Intro to Lettuce – the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library) - +- [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 5795e9912b..50d28af3d1 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -144,8 +144,8 @@ public class JedisIntegrationTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - scores.keySet().forEach(player -> { - jedis.zadd(key, scores.get(player), player); + scores.entrySet().forEach(playerScore -> { + jedis.zadd(key, playerScore.getValue(), playerScore.getKey()); }); Set players = jedis.zrevrange(key, 0, 1); diff --git a/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml b/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml index 4d677ab0d4..6ebc75de8d 100644 --- a/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml +++ b/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml @@ -3,10 +3,10 @@ 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 - com.baeldung.h2db spring-boot-h2-database 0.0.1-SNAPSHOT + spring-boot-h2-database jar Demo Spring Boot applications that starts H2 in memory database diff --git a/persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index f48199d4e8..0000000000 --- a/persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.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.h2db.demo.ClientSpringBootApp; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ClientSpringBootApp.class) -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-boot-persistence-mongodb/.gitignore b/persistence-modules/spring-boot-persistence-mongodb/.gitignore new file mode 100644 index 0000000000..f96dae6a60 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/.gitignore @@ -0,0 +1,4 @@ + +/.idea/ +/target/ +/spring-boot-persistence.iml diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md new file mode 100644 index 0000000000..f093d4baf0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -0,0 +1,3 @@ +# Relevant Articles + +- [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml new file mode 100644 index 0000000000..fc267eedf6 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + spring-boot-persistence-mongodb + war + spring-boot-persistence-mongodb + This is simple boot application for Spring boot persistence mongodb test + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + 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 + + + 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/java/com/baeldung/SpringBootPersistenceApplication.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/SpringBootPersistenceApplication.java new file mode 100644 index 0000000000..2dff3f37df --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/SpringBootPersistenceApplication.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootPersistenceApplication { + + public static void main(String ... args) { + SpringApplication.run(SpringBootPersistenceApplication.class, args); + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/UserRepository.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/UserRepository.java new file mode 100755 index 0000000000..7f58fdd1c8 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.mongodb.daos; + + +import com.baeldung.mongodb.models.User; +import org.springframework.data.mongodb.repository.MongoRepository; + + +public interface UserRepository extends MongoRepository { + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/events/UserModelListener.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/events/UserModelListener.java new file mode 100644 index 0000000000..24b53f3d2d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/events/UserModelListener.java @@ -0,0 +1,28 @@ +package com.baeldung.mongodb.events; + + +import com.baeldung.mongodb.models.User; +import com.baeldung.mongodb.services.SequenceGeneratorService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; +import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; +import org.springframework.stereotype.Component; + + +@Component +public class UserModelListener extends AbstractMongoEventListener { + + private SequenceGeneratorService sequenceGenerator; + + @Autowired + public UserModelListener(SequenceGeneratorService sequenceGenerator) { + this.sequenceGenerator = sequenceGenerator; + } + + @Override + public void onBeforeConvert(BeforeConvertEvent event) { + event.getSource().setId(sequenceGenerator.generateSequence(User.SEQUENCE_NAME)); + } + + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/DatabaseSequence.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/DatabaseSequence.java new file mode 100755 index 0000000000..c2c04f7ee6 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/DatabaseSequence.java @@ -0,0 +1,32 @@ +package com.baeldung.mongodb.models; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + + +@Document(collection = "database_sequences") +public class DatabaseSequence { + + @Id + private String id; + + private long seq; + + public DatabaseSequence() {} + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public long getSeq() { + return seq; + } + + public void setSeq(long seq) { + this.seq = seq; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/User.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/User.java new file mode 100755 index 0000000000..1f08074313 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/User.java @@ -0,0 +1,73 @@ +package com.baeldung.mongodb.models; + +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; +import org.springframework.data.mongodb.core.mapping.Document; + + +@Document(collection = "users") +public class User { + + @Transient + public static final String SEQUENCE_NAME = "users_sequence"; + + @Id + private long id; + + private String firstName; + + private String lastName; + + private String email; + + public User() { } + + public User(String firstName, String lastName, String email) { + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + } + + 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 email) { + this.email = email; + } + + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", email='" + email + '\'' + + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/SequenceGeneratorService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/SequenceGeneratorService.java new file mode 100755 index 0000000000..52ece27d63 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/SequenceGeneratorService.java @@ -0,0 +1,35 @@ +package com.baeldung.mongodb.services; + +import com.baeldung.mongodb.models.DatabaseSequence; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.MongoOperations; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +import java.util.Objects; + +import static org.springframework.data.mongodb.core.FindAndModifyOptions.options; +import static org.springframework.data.mongodb.core.query.Criteria.where; +import static org.springframework.data.mongodb.core.query.Query.query; + + +@Service +public class SequenceGeneratorService { + + + private MongoOperations mongoOperations; + + @Autowired + public SequenceGeneratorService(MongoOperations mongoOperations) { + this.mongoOperations = mongoOperations; + } + + public long generateSequence(String seqName) { + + DatabaseSequence counter = mongoOperations.findAndModify(query(where("_id").is(seqName)), + new Update().inc("seq",1), options().returnNew(true).upsert(true), + DatabaseSequence.class); + return !Objects.isNull(counter) ? counter.getSeq() : 1; + + } +} 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 new file mode 100644 index 0000000000..5b1b8000d0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.application.name=spring-boot-persistence +server.port=${PORT:0} + +#spring boot mongodb +spring.data.mongodb.host=localhost +spring.data.mongodb.port=27017 +spring.data.mongodb.database=springboot-mongo + diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbAutoGeneratedFieldIntegrationTest.java b/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbAutoGeneratedFieldIntegrationTest.java new file mode 100644 index 0000000000..cec1ad5fea --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbAutoGeneratedFieldIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.mongodb; + +import com.baeldung.mongodb.daos.UserRepository; +import com.baeldung.mongodb.models.User; +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.assertj.core.api.Assertions.assertThat; + + +@RunWith(SpringRunner.class) +@SpringBootTest +public class MongoDbAutoGeneratedFieldIntegrationTest { + + @Autowired + UserRepository userRepository; + + @Test + public void contextLoads() {} + + @Test + public void givenUserObject_whenSave_thenCreateNewUser() { + + User user = new User(); + user.setFirstName("John"); + user.setLastName("Doe"); + user.setEmail("john.doe@example.com"); + userRepository.save(user); + + assertThat(userRepository.findAll().size()).isGreaterThan(0); + } + + +} diff --git a/persistence-modules/spring-boot-persistence/README.MD b/persistence-modules/spring-boot-persistence/README.MD index 6cf172426a..8988fb4ebd 100644 --- a/persistence-modules/spring-boot-persistence/README.MD +++ b/persistence-modules/spring-boot-persistence/README.MD @@ -4,3 +4,4 @@ - [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source) - [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) - [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool) +- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 80472fdd57..d9d3a9f9b7 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -1,20 +1,18 @@ - + 4.0.0 - - com.baeldung spring-boot-persistence 0.1.0 - + spring-boot-persistence + parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 - + org.springframework.boot @@ -35,42 +33,30 @@ org.mockito mockito-core - ${mockito.version} test com.h2database h2 - ${h2database.version} runtime - + org.apache.tomcat tomcat-jdbc - ${tomcat-jdbc.version} mysql mysql-connector-java - ${mysql-connector-java.version} - - UTF-8 - 1.8 - 8.0.12 - 9.0.10 - 1.4.197 - 2.23.0 - - + spring-boot-persistence - - src/main/resources - true - + + src/main/resources + true + @@ -79,4 +65,14 @@ + + + UTF-8 + 1.8 + 8.0.12 + 9.0.10 + 1.4.197 + 2.23.0 + + diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index ef90714347..547a905d91 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -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.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "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" }); + em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java similarity index 95% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/domain/GenericEntity.java index f1c936e432..a2a676200a 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/domain/GenericEntity.java +++ b/persistence-modules/spring-boot-persistence/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/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java similarity index 63% rename from persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java rename to persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java index d897e17afe..bbc2865856 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/repository/GenericEntityRepository.java @@ -1,7 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.domain.GenericEntity; import org.springframework.data.jpa.repository.JpaRepository; +import com.baeldung.boot.domain.GenericEntity; + public interface GenericEntityRepository extends JpaRepository { } diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java new file mode 100644 index 0000000000..c5a5c291c6 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.springboothsqldb.application; + +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/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java new file mode 100644 index 0000000000..8229a1d1c0 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java @@ -0,0 +1,33 @@ +package com.baeldung.springboothsqldb.application.controllers; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import com.baeldung.springboothsqldb.application.repositories.CustomerRepository; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerController { + + private final CustomerRepository customerRepository; + + @Autowired + public CustomerController(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + @PostMapping("/customers") + public Customer addCustomer(@RequestBody Customer customer) { + customerRepository.save(customer); + return customer; + } + + @GetMapping("/customers") + public List getCustomers() { + return (List) customerRepository.findAll(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java new file mode 100644 index 0000000000..636a80e272 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.springboothsqldb.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private String email; + + public Customer() {} + + public Customer(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 String getName() { + return name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java new file mode 100644 index 0000000000..a81aa62c43 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.springboothsqldb.application.repositories; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository {} diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties index 303ce33c25..b0caf4a809 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence/src/main/resources/application.properties @@ -1,16 +1,5 @@ -spring.datasource.tomcat.initial-size=15 -spring.datasource.tomcat.max-wait=20000 -spring.datasource.tomcat.max-active=50 -spring.datasource.tomcat.max-idle=15 -spring.datasource.tomcat.min-idle=8 -spring.datasource.tomcat.default-auto-commit=true -spring.datasource.url=jdbc:h2:mem:test -spring.datasource.username=root -spring.datasource.password= -spring.datasource.driver-class-name=org.h2.Driver - -spring.jpa.show-sql=false -spring.jpa.hibernate.ddl-auto=update -spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect -spring.jpa.properties.hibernate.id.new_generator_mappings=false +spring.datasource.driver-class-name = org.hsqldb.jdbc.JDBCDriver +spring.datasource.url = jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1 +spring.datasource.username = sa +spring.datasource.password = +spring.jpa.hibernate.ddl-auto = create diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html index 2634e10380..344d4e59f5 100644 --- a/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html +++ b/persistence-modules/spring-boot-persistence/src/main/resources/templates/index.html @@ -40,4 +40,4 @@ - \ No newline at end of file + diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java index 6479e90113..ecacf62285 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootH2IntegrationTest.java @@ -3,8 +3,6 @@ package com.baeldung; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.baeldung.boot.domain.GenericEntity; -import org.baeldung.boot.repository.GenericEntityRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -12,10 +10,13 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.boot.config.H2JpaConfig; +import com.baeldung.boot.domain.GenericEntity; +import com.baeldung.boot.repository.GenericEntityRepository; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { Application.class, H2JpaConfig.class }) public class SpringBootH2IntegrationTest { + @Autowired private GenericEntityRepository genericEntityRepository; @@ -23,7 +24,9 @@ public class SpringBootH2IntegrationTest { public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() { GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test")); GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null); + assertNotNull(foundEntity); assertEquals(genericEntity.getValue(), foundEntity.getValue()); } + } \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java index eef9ebe953..01fae2fb4d 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootJPAIntegrationTest.java @@ -3,14 +3,15 @@ package com.baeldung; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.baeldung.boot.domain.GenericEntity; -import org.baeldung.boot.repository.GenericEntityRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.domain.GenericEntity; +import com.baeldung.boot.repository.GenericEntityRepository; + @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class SpringBootJPAIntegrationTest { diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java index 4c68f1d4a0..65a75d7bfe 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/SpringBootProfileIntegrationTest.java @@ -3,9 +3,6 @@ package com.baeldung; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.baeldung.boot.domain.GenericEntity; -import org.baeldung.boot.repository.GenericEntityRepository; -import org.baeldung.config.H2TestProfileJPAConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -13,6 +10,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.domain.GenericEntity; +import com.baeldung.boot.repository.GenericEntityRepository; +import com.baeldung.config.H2TestProfileJPAConfig; + @RunWith(SpringRunner.class) @SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class }) @ActiveProfiles("test") diff --git a/persistence-modules/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/config/H2TestProfileJPAConfig.java similarity index 91% rename from persistence-modules/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java rename to persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/config/H2TestProfileJPAConfig.java index 7f962e1417..bcbded95fb 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/org/baeldung/config/H2TestProfileJPAConfig.java +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/config/H2TestProfileJPAConfig.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.repository", "org.baeldung.boot.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.repository", "com.baeldung.boot.repository" }) @EnableTransactionManagement public class H2TestProfileJPAConfig { @@ -41,7 +41,7 @@ public class H2TestProfileJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.domain", "org.baeldung.boot.domain" }); + em.setPackagesToScan(new String[] { "com.baeldung.domain", "com.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java new file mode 100644 index 0000000000..33891e3d43 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.springboothsqldb.application.tests; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.nio.charset.Charset; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class CustomerControllerUnitTest { + + private static MediaType MEDIA_TYPE_JSON; + + @Autowired + private MockMvc mockMvc; + + @Before + public void setUpJsonMediaType() { + MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + } + + @Test + public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception { + Customer customer = new Customer("John", "john@domain.com"); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); + ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); + String requestJson = objectWriter.writeValueAsString(customer); + + this.mockMvc + .perform(MockMvcRequestBuilders.post("/customers") + .contentType(MEDIA_TYPE_JSON) + .content(requestJson) + ) + + .andExpect(MockMvcResultMatchers.status().isOk()); + } + + @Test + public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.get("/customers")) + + .andExpect(MockMvcResultMatchers.content().contentType(MEDIA_TYPE_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()); + } +} diff --git a/persistence-modules/spring-data-cassandra-reactive/README.md b/persistence-modules/spring-data-cassandra-reactive/README.md new file mode 100644 index 0000000000..87a61d46b3 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/README.md @@ -0,0 +1,3 @@ +#Relevant Articles + +- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive) diff --git a/persistence-modules/spring-data-cassandra-reactive/pom.xml b/persistence-modules/spring-data-cassandra-reactive/pom.xml new file mode 100644 index 0000000000..5303f9a53a --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + com.baeldung + spring-data-cassandra-reactive + 0.0.1-SNAPSHOT + jar + + spring-data-cassandra-reactive + Spring Data Cassandra reactive + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + UTF-8 + UTF-8 + + 1.8 + + + + + org.springframework.data + spring-data-cassandra + 2.1.2.RELEASE + + + io.projectreactor + reactor-core + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + + + diff --git a/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/SpringDataCassandraReactiveApplication.java b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/SpringDataCassandraReactiveApplication.java new file mode 100644 index 0000000000..5f467042a3 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/SpringDataCassandraReactiveApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.cassandra.reactive; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataCassandraReactiveApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringDataCassandraReactiveApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/controller/EmployeeController.java b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/controller/EmployeeController.java new file mode 100644 index 0000000000..e9de213e61 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/controller/EmployeeController.java @@ -0,0 +1,49 @@ +package com.baeldung.cassandra.reactive.controller; + +import com.baeldung.cassandra.reactive.model.Employee; +import com.baeldung.cassandra.reactive.service.EmployeeService; +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.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.List; + +@RestController +@RequestMapping("employee") +public class EmployeeController { + + @Autowired + EmployeeService employeeService; + + @PostConstruct + public void saveEmployees() { + List employees = new ArrayList<>(); + employees.add(new Employee(123, "John Doe", "Delaware", "jdoe@xyz.com", 31)); + employees.add(new Employee(324, "Adam Smith", "North Carolina", "asmith@xyz.com", 43)); + employees.add(new Employee(355, "Kevin Dunner", "Virginia", "kdunner@xyz.com", 24)); + employees.add(new Employee(643, "Mike Lauren", "New York", "mlauren@xyz.com", 41)); + employeeService.initializeEmployees(employees); + } + + @GetMapping("/list") + public Flux getAllEmployees() { + Flux employees = employeeService.getAllEmployees(); + return employees; + } + + @GetMapping("/{id}") + public Mono getEmployeeById(@PathVariable int id) { + return employeeService.getEmployeeById(id); + } + + @GetMapping("/filterByAge/{age}") + public Flux getEmployeesFilterByAge(@PathVariable int age) { + return employeeService.getEmployeesFilterByAge(age); + } +} diff --git a/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/model/Employee.java b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/model/Employee.java new file mode 100644 index 0000000000..a78f884778 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/model/Employee.java @@ -0,0 +1,20 @@ +package com.baeldung.cassandra.reactive.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.cassandra.core.mapping.PrimaryKey; +import org.springframework.data.cassandra.core.mapping.Table; + +@Table +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Employee { + @PrimaryKey + private int id; + private String name; + private String address; + private String email; + private int age; +} diff --git a/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/repository/EmployeeRepository.java b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/repository/EmployeeRepository.java new file mode 100644 index 0000000000..22dc2b4565 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/repository/EmployeeRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.cassandra.reactive.repository; + +import com.baeldung.cassandra.reactive.model.Employee; +import org.springframework.data.cassandra.repository.AllowFiltering; +import org.springframework.data.cassandra.repository.ReactiveCassandraRepository; +import reactor.core.publisher.Flux; + +public interface EmployeeRepository extends ReactiveCassandraRepository { + @AllowFiltering + Flux findByAgeGreaterThan(int age); +} diff --git a/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/service/EmployeeService.java b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/service/EmployeeService.java new file mode 100644 index 0000000000..40c330937a --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/main/java/com/baeldung/cassandra/reactive/service/EmployeeService.java @@ -0,0 +1,35 @@ +package com.baeldung.cassandra.reactive.service; + +import com.baeldung.cassandra.reactive.model.Employee; +import com.baeldung.cassandra.reactive.repository.EmployeeRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; + +@Service +public class EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + public void initializeEmployees(List employees) { + Flux savedEmployees = employeeRepository.saveAll(employees); + savedEmployees.subscribe(); + } + + public Flux getAllEmployees() { + Flux employees = employeeRepository.findAll(); + return employees; + } + + public Flux getEmployeesFilterByAge(int age) { + return employeeRepository.findByAgeGreaterThan(age); + } + + public Mono getEmployeeById(int id) { + return employeeRepository.findById(id); + } +} diff --git a/persistence-modules/spring-data-cassandra-reactive/src/main/resources/application.properties b/persistence-modules/spring-data-cassandra-reactive/src/main/resources/application.properties new file mode 100644 index 0000000000..7ed2f10131 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.data.cassandra.keyspace-name=practice +spring.data.cassandra.port=9042 \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-reactive/src/test/java/com/baeldung/cassandra/reactive/ReactiveEmployeeRepositoryIntegrationTest.java b/persistence-modules/spring-data-cassandra-reactive/src/test/java/com/baeldung/cassandra/reactive/ReactiveEmployeeRepositoryIntegrationTest.java new file mode 100644 index 0000000000..ad726fe969 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-reactive/src/test/java/com/baeldung/cassandra/reactive/ReactiveEmployeeRepositoryIntegrationTest.java @@ -0,0 +1,55 @@ +package com.baeldung.cassandra.reactive; + +import com.baeldung.cassandra.reactive.model.Employee; +import com.baeldung.cassandra.reactive.repository.EmployeeRepository; +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 reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ReactiveEmployeeRepositoryIntegrationTest { + + @Autowired + EmployeeRepository repository; + + @Before + public void setUp() { + + Flux deleteAndInsert = repository.deleteAll() // + .thenMany(repository.saveAll(Flux.just( + new Employee(111, "John Doe", "Delaware", "jdoe@xyz.com", 31), + new Employee(222, "Adam Smith", "North Carolina", "asmith@xyz.com", 43), + new Employee(333, "Kevin Dunner", "Virginia", "kdunner@xyz.com", 24), + new Employee(444, "Mike Lauren", "New York", "mlauren@xyz.com", 41)))); + + StepVerifier.create(deleteAndInsert).expectNextCount(4).verifyComplete(); + } + + @Test + public void givenRecordsAreInserted_whenDbIsQueried_thenShouldIncludeNewRecords() { + + Mono saveAndCount = repository.count() + .doOnNext(System.out::println) + .thenMany(repository.saveAll(Flux.just(new Employee(325, "Kim Jones", "Florida", "kjones@xyz.com", 42), + new Employee(654, "Tom Moody", "New Hampshire", "tmoody@xyz.com", 44)))) + .last() + .flatMap(v -> repository.count()) + .doOnNext(System.out::println); + + StepVerifier.create(saveAndCount).expectNext(6L).verifyComplete(); + } + + @Test + public void givenAgeForFilter_whenDbIsQueried_thenShouldReturnFilteredRecords() { + StepVerifier.create(repository.findByAgeGreaterThan(35)).expectNextCount(2).verifyComplete(); + } + +} diff --git a/persistence-modules/spring-data-gemfire/pom.xml b/persistence-modules/spring-data-gemfire/pom.xml index 34346c502f..dbb869acf0 100644 --- a/persistence-modules/spring-data-gemfire/pom.xml +++ b/persistence-modules/spring-data-gemfire/pom.xml @@ -2,9 +2,8 @@ 4.0.0 - com.baeldung spring-data-gemfire - 1.0.0-SNAPSHOT + spring-data-gemfire jar @@ -53,14 +52,6 @@ - - spring-snapshots - Spring Snapshots - http://repo.spring.io/libs-snapshot - - true - - gemstone http://dist.gemstone.com.s3.amazonaws.com/maven/release/ diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index 44ce240da3..3c71600565 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -15,6 +15,9 @@ - [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) - [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) +- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) +- [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) +- [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index 643210ab89..786e587734 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -5,6 +5,7 @@ 4.0.0 com.baeldung spring-data-jpa + spring-data-jpa parent-boot-2 diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java index 16407e510a..2bdd4e5451 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/config/PersistenceConfiguration.java @@ -1,13 +1,14 @@ package com.baeldung.config; -import com.baeldung.services.IBarService; -import com.baeldung.services.impl.BarSpringDataJpaService; -import com.google.common.base.Preconditions; -import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; -import com.baeldung.services.IFooService; -import com.baeldung.services.impl.FooService; +import java.util.Properties; + +import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @@ -20,13 +21,15 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; -import java.util.Properties; +import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl; +import com.baeldung.services.IBarService; +import com.baeldung.services.impl.BarSpringDataJpaService; +import com.google.common.base.Preconditions; @Configuration -@ComponentScan({"com.baeldung.dao", "com.baeldung.services"}) +@ComponentScan({ "com.baeldung.dao", "com.baeldung.services" }) @EnableTransactionManagement -@EnableJpaRepositories(basePackages = {"com.baeldung.dao"}, repositoryBaseClass = ExtendedRepositoryImpl.class) +@EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class) @EnableJpaAuditing @PropertySource("classpath:persistence.properties") public class PersistenceConfiguration { @@ -79,11 +82,6 @@ public class PersistenceConfiguration { return new BarSpringDataJpaService(); } - @Bean - public IFooService fooService() { - return new FooService(); - } - private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); @@ -94,7 +92,8 @@ public class PersistenceConfiguration { // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); // Envers properties - hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); + hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", + env.getProperty("envers.audit_table_suffix")); return hibernateProperties; } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonInsertRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonInsertRepository.java new file mode 100644 index 0000000000..d809385456 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonInsertRepository.java @@ -0,0 +1,30 @@ +package com.baeldung.dao.repositories.impl; + +import com.baeldung.domain.Person; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.Transactional; + +@Repository +public class PersonInsertRepository { + + @PersistenceContext + private EntityManager entityManager; + + @Transactional + public void insertWithQuery(Person person) { + entityManager.createNativeQuery("INSERT INTO person (id, first_name, last_name) VALUES (?,?,?)") + .setParameter(1, person.getId()) + .setParameter(2, person.getFirstName()) + .setParameter(3, person.getLastName()) + .executeUpdate(); + } + + @Transactional + public void insertWithEntityManager(Person person) { + this.entityManager.persist(person); + } + +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java old mode 100644 new mode 100755 index 7044d57e53..1f9f5f9195 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java @@ -1,8 +1,13 @@ package com.baeldung.dao.repositories.product; import com.baeldung.domain.product.Product; -import org.springframework.data.jpa.repository.JpaRepository; -public interface ProductRepository extends JpaRepository { +import java.util.List; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; + +public interface ProductRepository extends PagingAndSortingRepository { + + List findAllByPrice(double price, Pageable pageable); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/Person.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/Person.java new file mode 100644 index 0000000000..30d7370982 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/Person.java @@ -0,0 +1,47 @@ +package com.baeldung.domain; + +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 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; + } + +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java old mode 100644 new mode 100755 index 42e6dd8f45..2f82e3e318 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java @@ -19,6 +19,17 @@ public class 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; } @@ -46,7 +57,11 @@ public class Product { @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=").append(name).append(", id=").append(id).append("]"); + 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/limit/PassengerRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/PassengerRepository.java deleted file mode 100644 index 6301f6e307..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/PassengerRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.limit; - -import org.springframework.data.jpa.repository.JpaRepository; - -interface PassengerRepository extends JpaRepository, CustomPassengerRepository { - - Passenger findFirstByOrderBySeatNumberAsc(); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/CustomPassengerRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/CustomPassengerRepository.java similarity index 80% rename from persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/CustomPassengerRepository.java rename to persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/CustomPassengerRepository.java index e9b5ba272f..7ae44bfbda 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/CustomPassengerRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/CustomPassengerRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.limit; +package com.baeldung.passenger; import java.util.List; diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/Passenger.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/Passenger.java similarity index 80% rename from persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/Passenger.java rename to persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/Passenger.java index e7eb3af10b..24ae47e597 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/Passenger.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/Passenger.java @@ -1,4 +1,4 @@ -package com.baeldung.limit; +package com.baeldung.passenger; import javax.persistence.Basic; import javax.persistence.Column; @@ -17,7 +17,7 @@ class Passenger { @Basic(optional = false) @Column(nullable = false) - private String fistName; + private String firstName; @Basic(optional = false) @Column(nullable = false) @@ -27,8 +27,8 @@ class Passenger { @Column(nullable = false) private int seatNumber; - private Passenger(String fistName, String lastName, int seatNumber) { - this.fistName = fistName; + private Passenger(String firstName, String lastName, int seatNumber) { + this.firstName = firstName; this.lastName = lastName; this.seatNumber = seatNumber; } @@ -44,20 +44,20 @@ class Passenger { if (object == null || getClass() != object.getClass()) return false; Passenger passenger = (Passenger) object; - return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFistName(), passenger.getFistName()) + return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFirstName(), passenger.getFirstName()) && Objects.equals(getLastName(), passenger.getLastName()); } @Override public int hashCode() { - return Objects.hash(getFistName(), getLastName(), getSeatNumber()); + return Objects.hash(getFirstName(), getLastName(), getSeatNumber()); } @Override public String toString() { final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName()); toStringBuilder.append("{ id=").append(id); - toStringBuilder.append(", fistName='").append(fistName).append('\''); + toStringBuilder.append(", firstName='").append(firstName).append('\''); toStringBuilder.append(", lastName='").append(lastName).append('\''); toStringBuilder.append(", seatNumber=").append(seatNumber); toStringBuilder.append('}'); @@ -68,8 +68,8 @@ class Passenger { return id; } - String getFistName() { - return fistName; + String getFirstName() { + return firstName; } String getLastName() { diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/PassengerRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/PassengerRepository.java new file mode 100644 index 0000000000..6ae6afb403 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/PassengerRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.passenger; + +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +interface PassengerRepository extends JpaRepository, CustomPassengerRepository { + + Passenger findFirstByOrderBySeatNumberAsc(); + + List findByOrderBySeatNumberAsc(); + + List findByLastNameOrderBySeatNumberAsc(String lastName); + + List findByLastName(String lastName, Sort sort); +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/PassengerRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/PassengerRepositoryImpl.java similarity index 94% rename from persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/PassengerRepositoryImpl.java rename to persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/PassengerRepositoryImpl.java index 2d13eb7cad..bd6e535e3e 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/limit/PassengerRepositoryImpl.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/passenger/PassengerRepositoryImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.limit; +package com.baeldung.passenger; import org.springframework.stereotype.Repository; diff --git a/persistence-modules/spring-data-jpa/src/main/resources/application.properties b/persistence-modules/spring-data-jpa/src/main/resources/application.properties index 73d72bc7d6..37fb9ca9c4 100644 --- a/persistence-modules/spring-data-jpa/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa/src/main/resources/application.properties @@ -12,4 +12,6 @@ hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory -spring.datasource.data=import_entities.sql \ No newline at end of file +spring.datasource.data=import_entities.sql + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/test/resources/import_entities.sql b/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql similarity index 100% rename from persistence-modules/spring-data-jpa/src/test/resources/import_entities.sql rename to persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/PersonInsertRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/PersonInsertRepositoryIntegrationTest.java new file mode 100644 index 0000000000..b248cf8bf1 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/PersonInsertRepositoryIntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.dao.repositories.impl.PersonInsertRepository; +import com.baeldung.domain.Person; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.persistence.EntityExistsException; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceException; + +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +@RunWith(SpringRunner.class) +@DataJpaTest +@Import(PersonInsertRepository.class) +public class PersonInsertRepositoryIntegrationTest { + + private static final Long ID = 1L; + private static final String FIRST_NAME = "firstname"; + private static final String LAST_NAME = "lastname"; + private static final Person PERSON = new Person(ID, FIRST_NAME, LAST_NAME); + + @Autowired + private PersonInsertRepository personInsertRepository; + + @Autowired + private EntityManager entityManager; + + @Test + public void givenPersonEntity_whenInsertWithNativeQuery_ThenPersonIsPersisted() { + insertWithQuery(); + + assertPersonPersisted(); + } + + @Test + public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenPersistenceExceptionExceptionIsThrown() { + assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> { + insertWithQuery(); + insertWithQuery(); + }); + } + + @Test + public void givenPersonEntity_whenInsertWithEntityManager_thenPersonIsPersisted() { + insertPersonWithEntityManager(); + + assertPersonPersisted(); + } + + @Test + public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenEntityExistsExceptionIsThrown() { + assertThatExceptionOfType(EntityExistsException.class).isThrownBy(() -> { + insertPersonWithEntityManager(); + insertPersonWithEntityManager(); + }); + } + + private void insertWithQuery() { + personInsertRepository.insertWithQuery(PERSON); + } + + private void insertPersonWithEntityManager() { + personInsertRepository.insertWithEntityManager(new Person(ID, FIRST_NAME, LAST_NAME)); + } + + private void assertPersonPersisted() { + Person person = entityManager.find(Person.class, ID); + + assertThat(person).isNotNull(); + assertThat(person.getId()).isEqualTo(PERSON.getId()); + assertThat(person.getFirstName()).isEqualTo(PERSON.getFirstName()); + assertThat(person.getLastName()).isEqualTo(PERSON.getLastName()); + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4caa0f0ca4 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.dao.repositories.product; + +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.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.config.PersistenceProductConfiguration; +import com.baeldung.domain.product.Product; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceProductConfiguration.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/com/baeldung/limit/LimitIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/passenger/PassengerRepositoryIntegrationTest.java similarity index 63% rename from persistence-modules/spring-data-jpa/src/test/java/com/baeldung/limit/LimitIntegrationTest.java rename to persistence-modules/spring-data-jpa/src/test/java/com/baeldung/passenger/PassengerRepositoryIntegrationTest.java index 27e0ebdd9f..c57e771345 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/limit/LimitIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/passenger/PassengerRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.limit; +package com.baeldung.passenger; import org.junit.Before; import org.junit.Test; @@ -14,11 +14,13 @@ import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertEquals; @DataJpaTest @RunWith(SpringRunner.class) -public class LimitIntegrationTest { +public class PassengerRepositoryIntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -66,4 +68,31 @@ public class LimitIntegrationTest { Passenger actual = page.getContent().get(0); assertEquals(expected, actual); } + + @Test + public void givenPassengers_whenOrderedBySeatNumberAsc_thenCorrectOrder() { + Passenger fred = Passenger.from("Fred", "Bloggs", 22); + Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); + Passenger jill = Passenger.from("Jill", "Smith", 50); + Passenger siya = Passenger.from("Siya", "Kolisi", 85); + Passenger eve = Passenger.from("Eve", "Jackson", 95); + + List passengers = repository.findByOrderBySeatNumberAsc(); + + assertThat(passengers, contains(fred, ricki, jill, siya, eve)); + } + + @Test + public void givenPassengers_whenFindAllWithSortBySeatNumberAsc_thenCorrectOrder() { + Passenger fred = Passenger.from("Fred", "Bloggs", 22); + Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); + Passenger jill = Passenger.from("Jill", "Smith", 50); + Passenger siya = Passenger.from("Siya", "Kolisi", 85); + Passenger eve = Passenger.from("Eve", "Jackson", 95); + + List passengers = repository.findAll(Sort.by(Sort.Direction.ASC, "seatNumber")); + + assertThat(passengers, contains(fred, ricki, jill, siya, eve)); + } + } diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 0a60412813..7f906bdbcd 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -2,17 +2,12 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.Application; -import com.baeldung.config.PersistenceConfiguration; -import com.baeldung.config.PersistenceProductConfiguration; -import com.baeldung.config.PersistenceUserConfiguration; @RunWith(SpringRunner.class) -@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) @SpringBootTest(classes = Application.class) public class SpringContextIntegrationTest { diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java new file mode 100644 index 0000000000..66b5b20b97 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringJpaContextIntegrationTest.java @@ -0,0 +1,25 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = { + PersistenceConfiguration.class, + PersistenceUserConfiguration.class, + PersistenceProductConfiguration.class }) +@ContextConfiguration(classes = Application.class) +public class SpringJpaContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-keyvalue/pom.xml b/persistence-modules/spring-data-keyvalue/pom.xml index 6675595f2b..1fee0a88d4 100644 --- a/persistence-modules/spring-data-keyvalue/pom.xml +++ b/persistence-modules/spring-data-keyvalue/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-keyvalue + spring-data-keyvalue parent-boot-2 diff --git a/persistence-modules/spring-data-mongodb/README.md b/persistence-modules/spring-data-mongodb/README.md index c7bc7584be..c4f21dffc0 100644 --- a/persistence-modules/spring-data-mongodb/README.md +++ b/persistence-modules/spring-data-mongodb/README.md @@ -12,3 +12,4 @@ - [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations) - [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) - [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) diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index 76ec5a96a6..63b9c3c1b0 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -1,9 +1,7 @@ 4.0.0 - com.baeldung spring-data-mongodb - 0.0.1-SNAPSHOT spring-data-mongodb @@ -23,7 +21,7 @@ org.springframework.data spring-data-releasetrain - Lovelace-M3 + Lovelace-SR3 pom import @@ -76,17 +74,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - diff --git a/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml b/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml index 324f7f60c2..d59ebcef6e 100644 --- a/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml +++ b/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml @@ -7,33 +7,32 @@ http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/context - http://www.springframework.org/schema/context/spring-context.xsd" -> - - + http://www.springframework.org/schema/context/spring-context.xsd"> + + - + - + - + - + - + - + \ No newline at end of file diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveIntegrationTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveLiveTest.java similarity index 96% rename from persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveIntegrationTest.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveLiveTest.java index 43aa865e91..70908552fe 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveIntegrationTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionReactiveLiveTest.java @@ -14,7 +14,7 @@ import com.baeldung.model.User; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoReactiveConfig.class) -public class MongoTransactionReactiveIntegrationTest { +public class MongoTransactionReactiveLiveTest { @Autowired private ReactiveMongoOperations reactiveOps; diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateIntegrationTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java similarity index 97% rename from persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateIntegrationTest.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java index 1dbe724d87..20ac6974bc 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateIntegrationTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java @@ -26,7 +26,7 @@ import com.baeldung.model.User; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) -public class MongoTransactionTemplateIntegrationTest { +public class MongoTransactionTemplateLiveTest { @Autowired private MongoTemplate mongoTemplate; diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalIntegrationTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java similarity index 98% rename from persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalIntegrationTest.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java index 4d747789a0..0cf86aa43e 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalIntegrationTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java @@ -27,7 +27,7 @@ import com.mongodb.MongoCommandException; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class MongoTransactionalIntegrationTest { +public class MongoTransactionalLiveTest { @Autowired private MongoTemplate mongoTemplate; diff --git a/persistence-modules/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 04d549a288..0000000000 --- a/persistence-modules/spring-data-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.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 com.baeldung.config.MongoConfig; -import com.baeldung.config.SimpleMongoConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MongoConfig.class, SimpleMongoConfig.class }) -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml index 2be4df71be..1e5d51ddf2 100644 --- a/persistence-modules/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -3,7 +3,8 @@ 4.0.0 spring-data-neo4j 1.0 - + spring-data-neo4j + com.baeldung parent-modules diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index bee3d683b8..fb80b0413f 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -4,6 +4,7 @@ com.baeldung spring-data-redis 1.0 + spring-data-redis jar @@ -46,21 +47,9 @@ org.junit.jupiter junit-jupiter-api - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - test - org.junit.platform junit-platform-runner - ${junit.platform.version} test @@ -96,8 +85,6 @@ 0.10.0 2.0.3.RELEASE 0.6 - 1.0.0 - 5.0.2 diff --git a/persistence-modules/spring-hibernate-3/README.md b/persistence-modules/spring-hibernate-3/README.md index f9839e34bf..ac840b6f66 100644 --- a/persistence-modules/spring-hibernate-3/README.md +++ b/persistence-modules/spring-hibernate-3/README.md @@ -5,6 +5,7 @@ ### 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) ### Quick Start diff --git a/persistence-modules/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java b/persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java similarity index 100% rename from persistence-modules/spring-hibernate3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java rename to persistence-modules/spring-hibernate-3/src/main/java/org/baeldung/spring/PersistenceConfigHibernate3.java diff --git a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java similarity index 98% rename from persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java index bbbf074c1a..08032660c0 100644 --- a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen1MainIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.persistence.service; -import java.util.List; - import org.baeldung.persistence.model.Event; import org.baeldung.spring.PersistenceConfigHibernate3; import org.hamcrest.core.IsInstanceOf; diff --git a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java similarity index 98% rename from persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java rename to persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java index d8810f0e90..44cc6ca010 100644 --- a/persistence-modules/spring-hibernate3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/persistence/service/HibernateExceptionScen2MainIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.persistence.service; -import java.util.List; - import org.baeldung.persistence.model.Event; import org.baeldung.spring.PersistenceConfig; import org.hamcrest.core.IsInstanceOf; diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index b4d73708c3..5e287919f1 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -1,6 +1,5 @@ ### Relevant articles -- [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) - [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions) - [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) diff --git a/persistence-modules/spring-hibernate3/README.md b/persistence-modules/spring-hibernate3/README.md deleted file mode 100644 index 02928dfb51..0000000000 --- a/persistence-modules/spring-hibernate3/README.md +++ /dev/null @@ -1,2 +0,0 @@ -## Relevant articles: -- [HibernateException: No Hibernate Session Bound to Thread in Hibernate 3](http://www.baeldung.com/no-hibernate-session-bound-to-thread-exception) diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index b15b7278f4..57a341ed45 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -7,12 +7,10 @@ - [The DAO with Spring 3 and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) -- [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa) - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) - [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) -- [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) ### Quick Start diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java new file mode 100644 index 0000000000..372fb2fc07 --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; +import com.baeldung.hibernate.oneToMany.model.ItemsOIO; + +public class HibernateManyisOwningSide { + public static void main(String[] args) { + + Cart cart = new Cart(); + Cart cart2 = new Cart(); + + Items item1 = new Items(cart); + Items item2 = new Items(cart2); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + + item1 = (Items) session.get(Items.class, new Long(1)); + item2 = (Items) session.get(Items.class, new Long(2)); + tx.commit(); + + + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart() + .getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart() + .getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java new file mode 100644 index 0000000000..0777664dd0 --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java @@ -0,0 +1,67 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.CartOIO; +import com.baeldung.hibernate.oneToMany.model.ItemsOIO; + +public class HibernateOneisOwningSide { + public static void main(String[] args) { + + CartOIO cart = new CartOIO(); + CartOIO cart2 = new CartOIO(); + + ItemsOIO item1 = new ItemsOIO(cart); + ItemsOIO item2 = new ItemsOIO(cart2); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1)); + item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2)); + tx.commit(); + + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO() + .getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO() + .getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java new file mode 100644 index 0000000000..8a5ed5e7a4 --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java @@ -0,0 +1,42 @@ +package com.baeldung.hibernate.oneToMany.model; + +import java.util.Set; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.Table; + + + +@Entity +@Table(name = "CARTOIO") +public class CartOIO { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @OneToMany + @JoinColumn(name = "cart_id") // we need to duplicate the physical information + private Set items; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + +} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java new file mode 100644 index 0000000000..a3d6a796c5 --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.oneToMany.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "ITEMSOIO") +public class ItemsOIO { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @ManyToOne + @JoinColumn(name = "cart_id", insertable = false, updatable = false) + private CartOIO cart; + + // Hibernate requires no-args constructor + public ItemsOIO() { + } + + public ItemsOIO(CartOIO c) { + this.cart = c; + } + + public CartOIO getCartOIO() { + return cart; + } + + public void setCartOIO(CartOIO cart) { + this.cart = cart; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + +} diff --git a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml index 311300c77c..14d853d3fd 100644 --- a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml +++ b/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml @@ -9,11 +9,13 @@ jdbc:mysql://localhost:3306/spring_hibernate_one_to_many?createDatabaseIfNotExist=true myuser org.hibernate.dialect.MySQLDialect - + create thread true + + diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 299a5a1e51..e6f91ac016 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -19,6 +19,7 @@ - [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) - [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) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/pom.xml b/pom.xml index 5ebf7ba4f3..e8ff86665c 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,10 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - parent-modules + + lombok-custom + + parent-modules pom @@ -323,205 +326,245 @@ parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - asm - atomix - persistence-modules/apache-cayenne - aws - aws-lambda - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-sorting - annotations - apache-cxf - apache-fop - apache-geode - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper - apache-opennlp - autovalue - axon - azure - bootique - cdi - java-strings - - core-java - core-java-lang - core-java-arrays - core-java-collections - java-collections-conversions - java-collections-maps - core-java-io - core-java-8 - java-streams + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + autovalue + aws + aws-lambda + axon + azure + + bootique + + cas/cas-secured-app + cas/cas-server + cdi + checker-plugin + core-groovy + + + core-java-8 + + core-java-arrays + core-java-collections + core-java-collections-list + core-java-concurrency-basic + core-java-concurrency-collections + core-java-io + core-java-security + core-java-lang-syntax + core-java-lang + core-java-lang-oop + core-java-networking + core-java-perf + core-java-sun + core-scala + couchbase + custom-pmd + + dagger + data-structures + ddd + deeplearning4j + disruptor + dozer + drools + dubbo + + ethereum + + feign + flyway-cdi-extension + + + google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc + gson + guava + guava-collections + guava-modules/guava-18 + guava-modules/guava-19 + guava-modules/guava-21 + + guice + + hazelcast + helidon + httpclient + hystrix + + image-processing + immutables + + jackson + java-collections-conversions + java-collections-maps + + java-ee-8-security-api + java-lite + java-numbers + java-rmi + java-spi + java-streams + java-strings + java-vavr-stream + java-websocket + javafx + javax-servlets + javaxval + jaxb + + jee-7-security + jersey + JGit + jgroups + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta + + + kotlin-libraries + + + libraries-data + libraries-apache-commons + libraries-security + libraries-server + linkrest + logging-modules/log4j + logging-modules/log4j2 + logging-modules/logback + logging-modules/log-mdc + lombok + lucene + + mapstruct + maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis + + noexception + + optaplanner + orika + osgi + + patterns + pdf + performance-tests + + protobuffer + + persistence-modules/activejdbc + persistence-modules/apache-cayenne persistence-modules/core-java-persistence - core-kotlin - kotlin-libraries - core-groovy - core-java-concurrency - core-java-concurrency-collections - couchbase - persistence-modules/deltaspike - dozer - ethereum - feign - flips - testing-modules/groovy-spock - google-cloud - google-web-toolkit - gson - guava - guava-collections - guava-modules/guava-18 - guava-modules/guava-19 - guava-modules/guava-21 - guice - disruptor - core-scala - spring-static-resources - hazelcast - persistence-modules/hbase - persistence-modules/hibernate5 - httpclient - hystrix - image-processing - immutables - persistence-modules/influxdb - jackson - persistence-modules/java-cassandra - vavr - java-lite - java-numbers - java-rmi - java-vavr-stream - javax-servlets - javaxval - jaxb - javafx - jgroups - jee-7 - jee-7-security - jhipster - jjwt - jsf - json-path - json - jsoup - testing-modules/junit-5 - - libraries - libraries-data - libraries-security - libraries-server - linkrest - logging-modules/log-mdc - logging-modules/log4j - logging-modules/log4j2 - logging-modules/logback - lombok - mapstruct - metrics - maven - mesos-marathon - msf4j - testing-modules/mockito - testing-modules/mockito-2 - testing-modules/mocks - mustache - mvn-wrapper - noexception - persistence-modules/orientdb - osgi - orika - patterns - pdf - protobuffer - persistence-modules/querydsl - reactor-core - persistence-modules/redis - testing-modules/rest-assured - testing-modules/rest-testing - resteasy - rxjava - rxjava-2 - spring-swagger-codegen - testing-modules/selenium-junit-testng - persistence-modules/solr - spark-java - spring-4 - spring-5 - spring-5-data-reactive - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-5-reactive-oauth - spring-activiti - spring-akka - spring-amqp - spring-all - spring-amqp-simple - spring-apache-camel - spring-batch - spring-bom - spring-boot - spring-boot-client - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-ops - persistence-modules/spring-boot-persistence - spring-boot-security - spring-boot-mvc - spring-boot-vue - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-cloud-data-flow - spring-cloud - spring-cloud-bus - spring-core - spring-cucumber - spring-ejb - spring-aop - persistence-modules/spring-data-cassandra - persistence-modules/spring-data-couchbase-2 - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-elasticsearch - persistence-modules/spring-data-jpa - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-mongodb - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis - spring-data-rest - persistence-modules/spring-data-solr - spring-dispatcher-servlet - spring-exceptions - spring-freemarker - persistence-modules/spring-hibernate-3 - persistence-modules/spring-hibernate4 - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - spring-integration - spring-jenkins-pipeline - spring-jersey - jmeter - spring-jms - spring-jooq - persistence-modules/spring-jpa - ddd - + persistence-modules/deltaspike + persistence-modules/flyway + persistence-modules/hbase + persistence-modules/hibernate5 + persistence-modules/hibernate-ogm + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb + persistence-modules/java-jdbi + persistence-modules/java-jpa + persistence-modules/jnosql + persistence-modules/liquibase + persistence-modules/orientdb + persistence-modules/querydsl + persistence-modules/redis + persistence-modules/solr + persistence-modules/spring-boot-h2/spring-boot-h2-database + persistence-modules/spring-boot-persistence + persistence-modules/spring-boot-persistence-mongodb + persistence-modules/spring-data-cassandra + persistence-modules/spring-data-cassandra-reactive + persistence-modules/spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + + persistence-modules/spring-data-gemfire + persistence-modules/spring-data-jpa + persistence-modules/spring-data-keyvalue + persistence-modules/spring-data-mongodb + persistence-modules/spring-data-neo4j + persistence-modules/spring-data-redis + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-3 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-hibernate4 + persistence-modules/spring-jpa + + rabbitmq + + ratpack + reactor-core + rest-with-spark-java + resteasy + + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 + @@ -560,138 +603,118 @@ parent-java parent-kotlin - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - spring-zuul - spring-remoting - spring-reactor - spring-vertx - spring-jinq - spring-rest-embedded-tomcat - testing-modules/testing - testing-modules/testng - video-tutorials - xml - xmlunit-2 - struts-2 - apache-velocity - apache-solrj - rabbitmq - vertx - persistence-modules/spring-data-gemfire - mybatis - spring-drools - drools - persistence-modules/liquibase - spring-boot-property-exp - testing-modules/mockserver - testing-modules/test-containers - undertow - vaadin - vertx-and-rxjava saas - deeplearning4j - lucene - vraptor - persistence-modules/java-cockroachdb - spring-security-thymeleaf - persistence-modules/java-jdbi - jersey - java-spi - performance-tests - twilio - spring-boot-ctx-fluent - java-ee-8-security-api - spring-webflux-amqp - antlr - maven-archetype - optaplanner - apache-meecrowave - spring-reactive-kotlin - persistence-modules/jnosql + spark-java + + spring-4 + + spring-5 + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + + spring-activiti + spring-akka + spring-all + spring-amqp + spring-aop + spring-apache-camel + spring-batch + spring-bom + + spring-boot + spring-boot-admin spring-boot-angular-ecommerce - jta - - java-websocket - persistence-modules/activejdbc - animal-sniffer-mvn-plugin - apache-avro - apache-bval - apache-shiro - apache-spark - asciidoctor - checker-plugin - - - core-java-sun - custom-pmd - dagger - data-structures - dubbo - persistence-modules/flyway - - - jni - jooby - - - - ratpack - rest-with-spark-java 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-disable-console-logging + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-ops + spring-boot-property-exp + spring-boot-security + spring-boot-testing + spring-boot-vue + spring-boot-libraries + + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow + + spring-core + spring-cucumber + + spring-data-rest spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools + + spring-ejb + spring-exceptions + + spring-freemarker + spring-groovy + + spring-integration + + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq + + spring-kafka + spring-katharsis + + spring-ldap + spring-mobile - spring-mustache + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin spring-mvc-simple - spring-mybatis + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml + + spring-protobuf + + spring-quartz + + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-full spring-rest-hal-browser + spring-rest-query-language spring-rest-shell - spring-rest-template + spring-rest-simple + spring-resttemplate spring-roo - spring-security-stormpath - sse-jaxrs - static-analysis - stripe - - Twitter4J - wicket - xstream - cas/cas-secured-app - cas/cas-server - - - - - - - - - - - - - - - - - spring-boot-custom-starter/greeter - persistence-modules/spring-boot-h2/spring-boot-h2-database - - - - - flyway-cdi-extension spring-security-acl + spring-security-angular/server spring-security-cache-control + spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize spring-security-client/spring-security-jsp-config @@ -699,6 +722,7 @@ spring-security-client/spring-security-thymeleaf-authentication spring-security-client/spring-security-thymeleaf-authorize spring-security-client/spring-security-thymeleaf-config + spring-security-core spring-security-mvc-boot spring-security-mvc-custom @@ -709,33 +733,74 @@ spring-security-mvc-session spring-security-mvc-socket spring-security-openid - + + spring-security-rest spring-security-rest-basic-auth spring-security-rest-custom - spring-security-rest spring-security-sso + spring-security-stormpath + spring-security-thymeleaf spring-security-x509 + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen + + spring-thymeleaf + + spring-userservice + + spring-vault + spring-vertx + + spring-webflux-amqp + + spring-zuul + + static-analysis + stripe + structurizr + struts-2 + + testing-modules/gatling + testing-modules/groovy-spock + testing-modules/junit-5 + testing-modules/junit5-migration + testing-modules/load-testing-comparison + testing-modules/mockito + testing-modules/mockito-2 + testing-modules/mocks + testing-modules/mockserver + testing-modules/parallel-tests-junit + testing-modules/rest-assured + testing-modules/rest-testing + + testing-modules/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers + testing-modules/testing + testing-modules/testng + + twilio + Twitter4J + + undertow + + vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor + + wicket + + xml + xmlunit-2 + xstream - spring-kafka - spring-katharsis - spring-ldap - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml - spring-mvc-kotlin - spring-protobuf - spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - - - spring-resttemplate - helidon @@ -768,6 +833,7 @@ spring-5-reactive-client spring-5-reactive-security spring-5-security + spring-5-security-oauth spring-activiti spring-akka spring-all @@ -844,7 +910,6 @@ spring-remoting/remoting-rmi/remoting-rmi-server spring-rest spring-rest-angular - spring-rest-embedded-tomcat spring-rest-full spring-rest-simple spring-resttemplate @@ -883,7 +948,7 @@ spring-swagger-codegen/spring-swagger-codegen-app spring-thymeleaf spring-userservice - spring-vault + spring-vault spring-vertx spring-zuul/spring-zuul-foos-resource persistence-modules/spring-data-dynamodb @@ -894,347 +959,64 @@ - - integration - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - - - - - - - - - testing-modules/mockito - testing-modules/mockito-2 - testing-modules/mocks - mustache - mvn-wrapper - noexception - persistence-modules/orientdb - osgi - orika - patterns - pdf - protobuffer - persistence-modules/querydsl - reactor-core - persistence-modules/redis - testing-modules/rest-assured - testing-modules/rest-testing - resteasy - rxjava - rxjava-2 - spring-swagger-codegen - testing-modules/selenium-junit-testng - persistence-modules/solr - spark-java - spring-4 - spring-5 - spring-5-data-reactive - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client - spring-5-mvc - spring-5-security - spring-activiti - spring-akka - spring-amqp - spring-all - spring-amqp-simple - spring-apache-camel - spring-batch - jmh - - - - - - spring-bom - spring-boot - spring-boot-client - spring-boot-keycloak - spring-boot-bootstrap - spring-boot-admin - spring-boot-camel - spring-boot-ops - persistence-modules/spring-boot-persistence - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 - spring-boot-disable-console-logging - spring-cloud-data-flow - spring-cloud - spring-cloud-bus - spring-core - spring-cucumber - spring-ejb - spring-aop - persistence-modules/spring-data-cassandra - persistence-modules/spring-data-couchbase-2 - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-elasticsearch - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-mongodb - persistence-modules/spring-data-jpa - persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis - spring-data-rest - - - - - - - persistence-modules/spring-data-solr - spring-dispatcher-servlet - spring-exceptions - spring-freemarker - persistence-modules/spring-hibernate-3 - persistence-modules/spring-hibernate4 - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink - spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jms - spring-jooq - persistence-modules/spring-jpa - spring-kafka - spring-katharsis - spring-ldap - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml - spring-mvc-kotlin - spring-protobuf - spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - spring-rest - spring-resttemplate - spring-rest-simple - spring-reactive-kotlin - - - - - - - - - - - - - - - - java-websocket - persistence-modules/activejdbc - animal-sniffer-mvn-plugin - apache-avro - apache-bval - apache-shiro - apache-spark - asciidoctor - checker-plugin - - - core-java-sun - custom-pmd - dagger - data-structures - dubbo - persistence-modules/flyway - - - jni - jooby - - - - ratpack - rest-with-spark-java - spring-boot-autoconfiguration - spring-boot-custom-starter - spring-boot-jasypt - spring-data-rest-querydsl - spring-groovy - spring-mobile - spring-mustache - spring-mvc-simple - spring-mybatis - spring-rest-hal-browser - spring-rest-shell - spring-rest-template - spring-roo - spring-security-stormpath - sse-jaxrs - static-analysis - stripe - - - wicket - xstream - cas/cas-secured-app - - - - - - - - - - - - - - jenkins/hello-world - - - - spring-boot-custom-starter/greeter - persistence-modules/spring-boot-h2/spring-boot-h2-database - - - - - - - - - - integration-lite-test - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - - - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - spring-4 - - - - - integration-lite + default-heavy + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + core-java + core-java-concurrency-advanced + core-kotlin + + jenkins/hello-world + jhipster + jws + + libraries + + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql + + spring-5-data-reactive + spring-amqp-simple + + vaadin + + + + + integration-lite-first @@ -1262,196 +1044,384 @@ parent-spring-5 parent-java parent-kotlin - asm - atomix - persistence-modules/apache-cayenne - aws - aws-lambda + akka-streams algorithms-genetic algorithms-miscellaneous-1 algorithms-miscellaneous-2 algorithms-sorting + animal-sniffer-mvn-plugin annotations + antlr + apache-avro + apache-bval + apache-curator apache-cxf apache-fop - apache-poi - apache-tika - apache-thrift - apache-curator - apache-zookeeper + apache-geode + apache-meecrowave apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix autovalue + aws + aws-lambda axon azure - bootique - cdi - java-strings - - core-java-collections - java-collections-conversions - java-collections-maps - core-java-io - core-java-8 - java-streams - core-groovy + bootique + + cas/cas-secured-app + cas/cas-server + cdi + checker-plugin + core-groovy + + + core-java-8 + + core-java-arrays + core-java-collections + core-java-collections-list + core-java-concurrency-basic + core-java-concurrency-collections + core-java-io + core-java-security + core-java-lang-syntax + core-java-lang + core-java-lang-oop + core-java-networking + core-java-perf + core-java-sun + core-scala couchbase - persistence-modules/deltaspike + custom-pmd + + dagger + data-structures + ddd + deeplearning4j + disruptor dozer + drools + dubbo + ethereum + feign - flips - testing-modules/groovy-spock + flyway-cdi-extension + + google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc gson guava guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 + guice - disruptor - spring-static-resources + hazelcast - persistence-modules/hbase - + helidon + httpclient hystrix + image-processing immutables - persistence-modules/influxdb + jackson - vavr + java-collections-conversions + java-collections-maps + + java-ee-8-security-api java-lite java-numbers java-rmi + java-spi + java-streams + java-strings java-vavr-stream + java-websocket + javafx javax-servlets javaxval jaxb - javafx - jgroups - jee-7 + jee-7-security + jersey + JGit + jgroups + jib jjwt + jmeter + jmh + jni + jooby jsf - json-path json + json-path jsoup jta - testing-modules/junit-5 - testing-modules/junit5-migration - jws + + + kotlin-libraries + + libraries-data + libraries-apache-commons + libraries-security + libraries-server linkrest - logging-modules/log-mdc logging-modules/log4j - + logging-modules/log4j2 logging-modules/logback + logging-modules/log-mdc lombok - mapstruct + lucene + mapstruct maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + mesos-marathon + metrics + + microprofile msf4j - testing-modules/mockito - testing-modules/mockito-2 - testing-modules/mocks + mustache - mvn-wrapper + mybatis + noexception - persistence-modules/orientdb - osgi + + optaplanner orika + osgi + patterns pdf + performance-tests + protobuffer + + persistence-modules/activejdbc + persistence-modules/apache-cayenne + persistence-modules/core-java-persistence + persistence-modules/deltaspike + persistence-modules/flyway + persistence-modules/hbase + persistence-modules/hibernate5 + persistence-modules/hibernate-ogm + persistence-modules/influxdb + persistence-modules/java-cassandra + persistence-modules/java-cockroachdb + persistence-modules/java-jdbi + persistence-modules/java-jpa + persistence-modules/jnosql + persistence-modules/liquibase + persistence-modules/orientdb persistence-modules/querydsl - reactor-core persistence-modules/redis - testing-modules/rest-assured - testing-modules/rest-testing - resteasy - rxjava - rxjava-2 - spring-swagger-codegen - testing-modules/selenium-junit-testng persistence-modules/solr + persistence-modules/spring-boot-h2/spring-boot-h2-database + persistence-modules/spring-boot-persistence + persistence-modules/spring-boot-persistence-mongodb + persistence-modules/spring-data-cassandra + persistence-modules/spring-data-cassandra-reactive + persistence-modules/spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + + persistence-modules/spring-data-gemfire + persistence-modules/spring-data-jpa + persistence-modules/spring-data-keyvalue + persistence-modules/spring-data-mongodb + persistence-modules/spring-data-neo4j + persistence-modules/spring-data-redis + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-3 + persistence-modules/spring-hibernate-5 + persistence-modules/spring-hibernate4 + persistence-modules/spring-jpa + + rabbitmq + + ratpack + reactor-core + rest-with-spark-java + resteasy + + + rule-engines/easy-rules + rule-engines/openl-tablets + rule-engines/rulebook + rsocket + rxjava + rxjava-2 + + + + + + + integration-lite-second + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + saas spark-java + spring-4 - spring-5-data-reactive - spring-5-reactive - spring-5-reactive-security - spring-5-reactive-client + + spring-5 spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security spring-5-security + spring-5-security-oauth + spring-activiti spring-akka - spring-amqp spring-all - spring-amqp-simple + spring-amqp + spring-aop spring-apache-camel spring-batch spring-bom - spring-boot-keycloak - spring-boot-bootstrap + + spring-boot spring-boot-admin + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap spring-boot-camel - persistence-modules/spring-boot-persistence - spring-boot-security - spring-boot-mvc - spring-boot-logging-log4j2 + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter spring-boot-disable-console-logging - spring-cloud-data-flow + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-ops + spring-boot-property-exp + spring-boot-security + spring-boot-vue + spring-cloud spring-cloud-bus + + spring-cloud-data-flow + spring-core spring-cucumber - spring-ejb - spring-aop - - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-keyvalue - persistence-modules/spring-data-mongodb - persistence-modules/spring-data-neo4j - + spring-data-rest - persistence-modules/spring-data-solr + spring-data-rest-querydsl spring-dispatcher-servlet + spring-drools + + spring-ejb spring-exceptions + spring-freemarker - persistence-modules/spring-hibernate-3 - - persistence-modules/spring-hibernate-5 - persistence-modules/spring-data-eclipselink + + spring-groovy + spring-integration + spring-jenkins-pipeline spring-jersey - + spring-jinq spring-jms spring-jooq - persistence-modules/spring-jpa + spring-kafka spring-katharsis + spring-ldap + + spring-mobile spring-mockito spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple spring-mvc-velocity spring-mvc-webflow spring-mvc-xml - spring-mvc-kotlin + spring-protobuf + spring-quartz + + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest spring-rest-angular spring-rest-full + spring-rest-hal-browser spring-rest-query-language - spring-rest - spring-resttemplate + spring-rest-shell spring-rest-simple + spring-resttemplate + spring-roo + spring-security-acl + spring-security-angular/server spring-security-cache-control + spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize spring-security-client/spring-security-jsp-config @@ -1459,8 +1429,10 @@ spring-security-client/spring-security-thymeleaf-authentication spring-security-client/spring-security-thymeleaf-authorize spring-security-client/spring-security-thymeleaf-config + spring-security-core spring-security-mvc-boot + spring-security-mvc-custom spring-security-mvc-digest-auth spring-security-mvc-ldap spring-security-mvc-login @@ -1468,100 +1440,74 @@ spring-security-mvc-session spring-security-mvc-socket spring-security-openid - + + spring-security-rest spring-security-rest-basic-auth spring-security-rest-custom - spring-security-rest spring-security-sso + spring-security-stormpath + spring-security-thymeleaf spring-security-x509 spring-session spring-sleuth spring-social-login spring-spel spring-state-machine + spring-static-resources + spring-swagger-codegen + spring-thymeleaf + spring-userservice - spring-zuul - spring-remoting - spring-reactor - spring-vertx + spring-vault - spring-jinq - spring-rest-embedded-tomcat + spring-vertx + + spring-webflux-amqp + + spring-zuul + + static-analysis + stripe + structurizr + struts-2 + + testing-modules/gatling + testing-modules/groovy-spock + testing-modules/junit-5 + testing-modules/junit5-migration + testing-modules/load-testing-comparison + testing-modules/mockito + testing-modules/mockito-2 + testing-modules/mocks + testing-modules/mockserver + testing-modules/parallel-tests-junit + testing-modules/rest-assured + testing-modules/rest-testing + + testing-modules/selenium-junit-testng + testing-modules/spring-testing + testing-modules/test-containers testing-modules/testing testing-modules/testng - video-tutorials - - xmlunit-2 - struts-2 - apache-velocity - apache-solrj - rabbitmq - - persistence-modules/spring-data-gemfire - mybatis - spring-drools - drools - persistence-modules/liquibase - spring-boot-property-exp - testing-modules/mockserver - testing-modules/test-containers - undertow - vaadin - vertx-and-rxjava - saas - deeplearning4j - lucene - vraptor - persistence-modules/java-cockroachdb - spring-security-thymeleaf - persistence-modules/java-jdbi - jersey - java-spi - performance-tests + twilio - spring-boot-ctx-fluent - java-ee-8-security-api - spring-webflux-amqp - antlr - maven-archetype - apache-meecrowave - - persistence-modules/spring-hibernate4 - xml + Twitter4J + + undertow + + vavr vertx - metrics - httpclient - - - - - - - - + vertx-and-rxjava + video-tutorials + vraptor + + wicket + + xml + xmlunit-2 + xstream + @@ -1594,23 +1540,27 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin - libraries - geotools + parent-kotlin + + core-java + core-java-concurrency-advanced + core-kotlin + + jenkins/hello-world jhipster - testing-modules/gatling - spring-boot - spring-boot-ops - spring-5 - core-kotlin - kotlin-libraries - core-java - google-web-toolkit - spring-security-mvc-custom + jws + + libraries + persistence-modules/hibernate5 - persistence-modules/spring-data-elasticsearch - core-java-concurrency - core-java-concurrency-collections + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql + + spring-5-data-reactive + spring-amqp-simple + + vaadin @@ -1635,7 +1585,7 @@ true false false - + false 4.12 1.3 @@ -1666,7 +1616,7 @@ 2.3.1 1.9.13 1.2 - 2.5.0 + 2.9.7 1.3 1.2.0 5.2.0 diff --git a/protobuffer/pom.xml b/protobuffer/pom.xml index ff443a1615..d9e6cb26e4 100644 --- a/protobuffer/pom.xml +++ b/protobuffer/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 protobuffer - + protobuffer + parent-modules com.baeldung diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index cf720ad6ea..db9550df7b 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -1,11 +1,11 @@ 4.0.0 - org.baeldung reactor-core 0.0.1-SNAPSHOT - + reactor-core + com.baeldung parent-modules diff --git a/rest-with-spark-java/pom.xml b/rest-with-spark-java/pom.xml index a0005b7dec..f7c91f8827 100644 --- a/rest-with-spark-java/pom.xml +++ b/rest-with-spark-java/pom.xml @@ -34,8 +34,8 @@ 2.5.4 - 2.8.6 - 2.8.6 + 2.9.7 + 2.9.7 diff --git a/resteasy/bin/README.md b/resteasy/bin/README.md index 722f1dfe93..f4dba1493a 100644 --- a/resteasy/bin/README.md +++ b/resteasy/bin/README.md @@ -4,5 +4,3 @@ ### Relevant Articles: -- [A Guide to RESTEasy](http://www.baeldung.com/resteasy-tutorial) -- [RESTEasy Client API](http://www.baeldung.com/resteasy-client-tutorial) diff --git a/restx/README.md b/restx/README.md new file mode 100644 index 0000000000..665f7ea82d --- /dev/null +++ b/restx/README.md @@ -0,0 +1,4 @@ +# Relevant Articles + +* [Introduction to RESTX](https://www.baeldung.com/java-restx) + diff --git a/restx/data/credentials.json b/restx/data/credentials.json new file mode 100644 index 0000000000..c1a4fcf531 --- /dev/null +++ b/restx/data/credentials.json @@ -0,0 +1,12 @@ +{ + "//": "lines with // keys are just comments (we don't have real comments in json)", + "//": "this file stores password passed through md5+bcrypt hash", + "//": "you can use `restx hash md5+bcrypt {password}` shell command to get hashed passwords to put here", + + "//": "to help startup with restx, there are comments with clear text passwords,", + "//": "which should obviously not be stored here.", + "user1": "$2a$10$iZluFUJShbjb1ue68bLrDuGCeJL9EMLHelVIf8u0SUbCseDOvKnoe", + "//": "user 1 password is 'user1-pwd'", + "user2": "$2a$10$oym3SYMFXf/9gGfDKKHO4eM1vWNqAZMsRZCL.BORCaP4yp5cdiCXu", + "//": "user 2 password is 'user2-pwd'" +} \ No newline at end of file diff --git a/restx/data/users.json b/restx/data/users.json new file mode 100644 index 0000000000..834e03c4b4 --- /dev/null +++ b/restx/data/users.json @@ -0,0 +1,4 @@ +[ + {"name":"user1", "roles": ["hello"]}, + {"name":"user2", "roles": []} +] \ No newline at end of file diff --git a/restx/md.restx.json b/restx/md.restx.json new file mode 100644 index 0000000000..c87244001c --- /dev/null +++ b/restx/md.restx.json @@ -0,0 +1,38 @@ +{ + "module": "restx-demo:restx-demo:0.1-SNAPSHOT", + "packaging": "war", + + "properties": { + "java.version": "1.8", + "restx.version": "0.35-rc4" + }, + "fragments": { + "maven": [ + "classpath:///restx/build/fragments/maven/javadoc-apidoclet.xml" ] + }, + "dependencies": { + "compile": [ + "io.restx:restx-core:${restx.version}", + "io.restx:restx-security-basic:${restx.version}", + "io.restx:restx-core-annotation-processor:${restx.version}", + "io.restx:restx-factory:${restx.version}", + "io.restx:restx-factory-admin:${restx.version}", + "io.restx:restx-validation:${restx.version}", + "io.restx:restx-monitor-codahale:${restx.version}", + "io.restx:restx-monitor-admin:${restx.version}", + "io.restx:restx-log-admin:${restx.version}", + "io.restx:restx-i18n-admin:${restx.version}", + "io.restx:restx-stats-admin:${restx.version}", + "io.restx:restx-servlet:${restx.version}", + "io.restx:restx-server-jetty8:${restx.version}!optional", + "io.restx:restx-apidocs:${restx.version}", + "io.restx:restx-specs-admin:${restx.version}", + "io.restx:restx-admin:${restx.version}", + "ch.qos.logback:logback-classic:1.0.13" + ], + "test": [ + "io.restx:restx-specs-tests:${restx.version}", + "junit:junit:4.11" + ] + } +} diff --git a/restx/pom.xml b/restx/pom.xml new file mode 100644 index 0000000000..c6233b968c --- /dev/null +++ b/restx/pom.xml @@ -0,0 +1,155 @@ + + + 4.0.0 + + restx + 0.1-SNAPSHOT + war + restx-demo + + + 1.8 + 1.8 + 0.35-rc4 + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.restx + restx-core + ${restx.version} + + + io.restx + restx-security-basic + ${restx.version} + + + io.restx + restx-core-annotation-processor + ${restx.version} + + + io.restx + restx-factory + ${restx.version} + + + io.restx + restx-factory-admin + ${restx.version} + + + io.restx + restx-validation + ${restx.version} + + + io.restx + restx-monitor-codahale + ${restx.version} + + + io.restx + restx-monitor-admin + ${restx.version} + + + io.restx + restx-log-admin + ${restx.version} + + + io.restx + restx-i18n-admin + ${restx.version} + + + io.restx + restx-stats-admin + ${restx.version} + + + io.restx + restx-servlet + ${restx.version} + + + io.restx + restx-server-jetty8 + ${restx.version} + true + + + io.restx + restx-apidocs + ${restx.version} + + + io.restx + restx-specs-admin + ${restx.version} + + + io.restx + restx-admin + ${restx.version} + + + ch.qos.logback + logback-classic + 1.0.13 + + + io.restx + restx-specs-tests + ${restx.version} + test + + + junit + junit + 4.11 + test + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + attach-docs + + prepare-package + + jar + + + + + ${maven.compiler.source} + restx.apidocs.doclet.ApidocsDoclet + + io.restx + restx-apidocs-doclet + ${restx.version} + + -restx-target-dir ${project.basedir}/target/classes + + + + + diff --git a/restx/src/main/java/restx/demo/AppModule.java b/restx/src/main/java/restx/demo/AppModule.java new file mode 100644 index 0000000000..26bc681481 --- /dev/null +++ b/restx/src/main/java/restx/demo/AppModule.java @@ -0,0 +1,74 @@ +package restx.demo; + +import restx.config.ConfigLoader; +import restx.config.ConfigSupplier; +import restx.factory.Provides; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; +import com.google.common.collect.ImmutableSet; +import restx.security.*; +import restx.factory.Module; +import restx.factory.Provides; +import javax.inject.Named; + +import java.nio.file.Paths; + +@Module +public class AppModule { + @Provides + public SignatureKey signatureKey() { + return new SignatureKey("restx-demo -447494532235718370 restx-demo 801c9eaf-4116-48f2-906b-e979fba72757".getBytes(Charsets.UTF_8)); + } + + @Provides + @Named("restx.admin.password") + public String restxAdminPassword() { + return "4780"; + } + + @Provides + public ConfigSupplier appConfigSupplier(ConfigLoader configLoader) { + // Load settings.properties in restx.demo package as a set of config entries + return configLoader.fromResource("restx/demo/settings"); + } + + @Provides + public CredentialsStrategy credentialsStrategy() { + return new BCryptCredentialsStrategy(); + } + + @Provides + public BasicPrincipalAuthenticator basicPrincipalAuthenticator( + SecuritySettings securitySettings, CredentialsStrategy credentialsStrategy, + @Named("restx.admin.passwordHash") String defaultAdminPasswordHash, ObjectMapper mapper) { + return new StdBasicPrincipalAuthenticator(new StdUserService<>( + // use file based users repository. + // Developer's note: prefer another storage mechanism for your users if you need real user management + // and better perf + new FileBasedUserRepository<>( + StdUser.class, // this is the class for the User objects, that you can get in your app code + // with RestxSession.current().getPrincipal().get() + // it can be a custom user class, it just need to be json deserializable + mapper, + + // this is the default restx admin, useful to access the restx admin console. + // if one user with restx-admin role is defined in the repository, this default user won't be + // available anymore + new StdUser("admin", ImmutableSet.of("*")), + + // the path where users are stored + Paths.get("data/users.json"), + + // the path where credentials are stored. isolating both is a good practice in terms of security + // it is strongly recommended to follow this approach even if you use your own repository + Paths.get("data/credentials.json"), + + // tells that we want to reload the files dynamically if they are touched. + // this has a performance impact, if you know your users / credentials never change without a + // restart you can disable this to get better perfs + true), + credentialsStrategy, defaultAdminPasswordHash), + securitySettings); + } +} diff --git a/restx/src/main/java/restx/demo/AppServer.java b/restx/src/main/java/restx/demo/AppServer.java new file mode 100644 index 0000000000..d66aadac68 --- /dev/null +++ b/restx/src/main/java/restx/demo/AppServer.java @@ -0,0 +1,32 @@ +package restx.demo; + +import com.google.common.base.Optional; +import restx.server.WebServer; +import restx.server.Jetty8WebServer; + +/** + * This class can be used to run the app. + * + * Alternatively, you can deploy the app as a war in a regular container like tomcat or jetty. + * + * Reading the port from system env PORT makes it compatible with heroku. + */ +public class AppServer { + public static final String WEB_INF_LOCATION = "src/main/webapp/WEB-INF/web.xml"; + public static final String WEB_APP_LOCATION = "src/main/webapp"; + + public static void main(String[] args) throws Exception { + int port = Integer.valueOf(Optional.fromNullable(System.getenv("PORT")).or("8080")); + WebServer server = new Jetty8WebServer(WEB_INF_LOCATION, WEB_APP_LOCATION, port, "0.0.0.0"); + + /* + * load mode from system property if defined, or default to dev + * be careful with that setting, if you use this class to launch your server in production, make sure to launch + * it with -Drestx.mode=prod or change the default here + */ + System.setProperty("restx.mode", System.getProperty("restx.mode", "dev")); + System.setProperty("restx.app.package", "restx.demo"); + + server.startAndAwait(); + } +} diff --git a/restx/src/main/java/restx/demo/Roles.java b/restx/src/main/java/restx/demo/Roles.java new file mode 100644 index 0000000000..1240da70d1 --- /dev/null +++ b/restx/src/main/java/restx/demo/Roles.java @@ -0,0 +1,10 @@ +package restx.demo; + +/** + * A list of roles for the application. + * + * We don't use an enum here because it must be used inside an annotation. + */ +public final class Roles { + public static final String HELLO_ROLE = "hello"; +} diff --git a/restx/src/main/java/restx/demo/domain/Message.java b/restx/src/main/java/restx/demo/domain/Message.java new file mode 100644 index 0000000000..733c00deff --- /dev/null +++ b/restx/src/main/java/restx/demo/domain/Message.java @@ -0,0 +1,21 @@ +package restx.demo.domain; + +public class Message { + private String message; + + public String getMessage() { + return message; + } + + public Message setMessage(final String message) { + this.message = message; + return this; + } + + @Override + public String toString() { + return "Message{" + + "message='" + message + '\'' + + '}'; + } +} diff --git a/restx/src/main/java/restx/demo/rest/HelloResource.java b/restx/src/main/java/restx/demo/rest/HelloResource.java new file mode 100644 index 0000000000..5cb2c2a5e6 --- /dev/null +++ b/restx/src/main/java/restx/demo/rest/HelloResource.java @@ -0,0 +1,62 @@ +package restx.demo.rest; + +import restx.demo.domain.Message; +import restx.demo.Roles; +import org.joda.time.DateTime; +import restx.annotations.GET; +import restx.annotations.POST; +import restx.annotations.RestxResource; +import restx.factory.Component; +import restx.security.PermitAll; +import restx.security.RolesAllowed; +import restx.security.RestxSession; + +import javax.validation.constraints.NotNull; + +@Component @RestxResource +public class HelloResource { + + /** + * Say hello to currently logged in user. + * + * Authorized only for principals with Roles.HELLO_ROLE role. + * + * @return a Message to say hello + */ + @GET("/message") + @RolesAllowed(Roles.HELLO_ROLE) + public Message sayHello() { + return new Message().setMessage(String.format( + "hello %s, it's %s", + RestxSession.current().getPrincipal().get().getName(), + DateTime.now().toString("HH:mm:ss"))); + } + + /** + * Say hello to anybody. + * + * Does not require authentication. + * + * @return a Message to say hello + */ + @GET("/hello") + @PermitAll + public Message helloPublic(String who) { + return new Message().setMessage(String.format( + "hello %s, it's %s", + who, DateTime.now().toString("HH:mm:ss"))); + } + + public static class MyPOJO { + @NotNull + String value; + public String getValue(){ return value; } + public void setValue(String value){ this.value = value; } + } + @POST("/mypojo") + @PermitAll + public MyPOJO helloPojo(MyPOJO pojo){ + pojo.setValue("hello "+pojo.getValue()); + return pojo; + } +} diff --git a/restx/src/main/resources/logback.xml b/restx/src/main/resources/logback.xml new file mode 100644 index 0000000000..524bca6b1f --- /dev/null +++ b/restx/src/main/resources/logback.xml @@ -0,0 +1,94 @@ + + + true + + + + + ${LOGS_FOLDER}/errors.log + + ERROR + + + %d [%-16thread] [%-10X{principal}] %-5level %logger{36} - %msg%n + + + ${LOGS_FOLDER}/errors.%d.log + 30 + + + + + + + + ${LOGS_FOLDER}/app.log + + INFO + + + %d [%-16thread] [%-10X{principal}] %-5level %logger{36} - %msg%n + + + ${LOGS_FOLDER}/app.%d.log + 10 + + + + ${LOGS_FOLDER}/debug.log + + %d [%-16thread] [%-10X{principal}] %-5level %logger{36} - %msg%n + + + ${LOGS_FOLDER}/debug.%i.log.zip + 1 + 3 + + + + 50MB + + + + + + + + + + + + %d [%-16thread] [%-10X{principal}] %-5level %logger{36} - %msg%n + + + + ${LOGS_FOLDER}/app.log + + %d [%-16thread] [%-10X{principal}] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/restx/src/main/resources/restx/demo/settings.properties b/restx/src/main/resources/restx/demo/settings.properties new file mode 100644 index 0000000000..a03c2eea97 --- /dev/null +++ b/restx/src/main/resources/restx/demo/settings.properties @@ -0,0 +1 @@ +app.name=restx-demo \ No newline at end of file diff --git a/restx/src/main/webapp/WEB-INF/web.xml b/restx/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..c651794526 --- /dev/null +++ b/restx/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + restx + restx.servlet.RestxMainRouterServlet + 1 + + + restx + /api/* + + diff --git a/restx/src/test/java/restx/demo/rest/HelloResourceSpecUnitTest.java b/restx/src/test/java/restx/demo/rest/HelloResourceSpecUnitTest.java new file mode 100644 index 0000000000..f67e4565b3 --- /dev/null +++ b/restx/src/test/java/restx/demo/rest/HelloResourceSpecUnitTest.java @@ -0,0 +1,23 @@ +package restx.demo.rest; + +import org.junit.runner.RunWith; + +import restx.tests.FindSpecsIn; +import restx.tests.RestxSpecTestsRunner; + +@RunWith(RestxSpecTestsRunner.class) +@FindSpecsIn("specs/hello") +public class HelloResourceSpecUnitTest { + + /** + * Useless, thanks to both @RunWith(RestxSpecTestsRunner.class) & @FindSpecsIn() + * + * @Rule + * public RestxSpecRule rule = new RestxSpecRule(); + * + * @Test + * public void test_spec() throws Exception { + * rule.runTest(specTestPath); + * } + */ +} diff --git a/restx/src/test/resources/specs/hello/should_admin_say_hello.spec.yaml b/restx/src/test/resources/specs/hello/should_admin_say_hello.spec.yaml new file mode 100644 index 0000000000..1b7b8f0f90 --- /dev/null +++ b/restx/src/test/resources/specs/hello/should_admin_say_hello.spec.yaml @@ -0,0 +1,10 @@ +title: should admin say hello +given: + - time: 2013-08-28T01:18:00.822+02:00 + - uuids: [ "e2b4430f-9541-4602-9a3a-413d17c56a6b" ] +wts: + - when: | + GET message + $RestxSession: {"_expires":"2013-09-27T01:18:00.822+02:00","principal":"admin","sessionKey":"e2b4430f-9541-4602-9a3a-413d17c56a6b"} + then: | + {"message":"hello admin, it's 01:18:00"} diff --git a/restx/src/test/resources/specs/hello/should_anyone_say_hello.spec.yaml b/restx/src/test/resources/specs/hello/should_anyone_say_hello.spec.yaml new file mode 100644 index 0000000000..29b6faca34 --- /dev/null +++ b/restx/src/test/resources/specs/hello/should_anyone_say_hello.spec.yaml @@ -0,0 +1,8 @@ +title: should admin say hello +given: + - time: 2013-08-28T01:18:00.822+02:00 +wts: + - when: | + GET hello?who=xavier + then: | + {"message":"hello xavier, it's 01:18:00"} diff --git a/restx/src/test/resources/specs/hello/should_missing_value_triggers_validation_error.spec.yaml b/restx/src/test/resources/specs/hello/should_missing_value_triggers_validation_error.spec.yaml new file mode 100644 index 0000000000..d0c6323caf --- /dev/null +++ b/restx/src/test/resources/specs/hello/should_missing_value_triggers_validation_error.spec.yaml @@ -0,0 +1,17 @@ +title: should missing post value triggers a validation error +given: + - time: 2013-08-28T01:18:00.822+02:00 + - uuids: [ "e2b4430f-9541-4602-9a3a-413d17c56a6b" ] +wts: + - when: | + POST mypojo + $RestxSession: {"_expires":"2013-09-27T01:18:00.822+02:00","principal":"user1","sessionKey":"e2b4430f-9541-4602-9a3a-413d17c56a6b"} + {} + then: | + 400 + - when: | + POST mypojo + $RestxSession: {"_expires":"2013-09-27T01:18:00.822+02:00","principal":"user1","sessionKey":"e2b4430f-9541-4602-9a3a-413d17c56a6b"} + {"value":"world"} + then: | + {"value":"hello world"} diff --git a/restx/src/test/resources/specs/hello/should_user1_say_hello.spec.yaml b/restx/src/test/resources/specs/hello/should_user1_say_hello.spec.yaml new file mode 100644 index 0000000000..791a3a2776 --- /dev/null +++ b/restx/src/test/resources/specs/hello/should_user1_say_hello.spec.yaml @@ -0,0 +1,10 @@ +title: should user1 say hello +given: + - time: 2013-08-28T01:18:00.822+02:00 + - uuids: [ "e2b4430f-9541-4602-9a3a-413d17c56a6b" ] +wts: + - when: | + GET message + $RestxSession: {"_expires":"2013-09-27T01:18:00.822+02:00","principal":"user1","sessionKey":"e2b4430f-9541-4602-9a3a-413d17c56a6b"} + then: | + {"message":"hello user1, it's 01:18:00"} diff --git a/restx/src/test/resources/specs/hello/should_user2_not_say_hello.spec.yaml b/restx/src/test/resources/specs/hello/should_user2_not_say_hello.spec.yaml new file mode 100644 index 0000000000..ead5af8d0c --- /dev/null +++ b/restx/src/test/resources/specs/hello/should_user2_not_say_hello.spec.yaml @@ -0,0 +1,10 @@ +title: should user2 not say hello +given: + - time: 2013-08-28T01:19:44.770+02:00 + - uuids: [ "56f71fcc-42d3-422f-9458-8ad37fc4a0b5" ] +wts: + - when: | + GET message + $RestxSession: {"_expires":"2013-09-27T01:19:44.770+02:00","principal":"user2","sessionKey":"56f71fcc-42d3-422f-9458-8ad37fc4a0b5"} + then: | + 403 diff --git a/rmi/README.md b/rmi/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/rmi/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/rmi/client.policy b/rmi/client.policy deleted file mode 100644 index 5d74bde76d..0000000000 --- a/rmi/client.policy +++ /dev/null @@ -1,3 +0,0 @@ -grant { - permission java.security.AllPermission; -}; \ No newline at end of file diff --git a/rmi/server.policy b/rmi/server.policy deleted file mode 100644 index 5d74bde76d..0000000000 --- a/rmi/server.policy +++ /dev/null @@ -1,3 +0,0 @@ -grant { - permission java.security.AllPermission; -}; \ No newline at end of file diff --git a/rmi/src/org/baeldung/Client.java b/rmi/src/org/baeldung/Client.java deleted file mode 100644 index 0376952bab..0000000000 --- a/rmi/src/org/baeldung/Client.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung; - -import java.rmi.NotBoundException; -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; - -public class Client { - public static void main(String[] args) throws RemoteException, NotBoundException { - System.setProperty("java.security.policy", "file:./client.policy"); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } - String name = "RandomNumberGenerator"; - Registry registry = LocateRegistry.getRegistry(); - RandomNumberGenerator randomNumberGenerator = (RandomNumberGenerator) registry.lookup(name); - int number = randomNumberGenerator.get(); - System.out.println("Received random number:" + number); - } -} diff --git a/rmi/src/org/baeldung/RandomNumberGenerator.java b/rmi/src/org/baeldung/RandomNumberGenerator.java deleted file mode 100644 index 50e49d2652..0000000000 --- a/rmi/src/org/baeldung/RandomNumberGenerator.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung; - -import java.rmi.Remote; -import java.rmi.RemoteException; - -public interface RandomNumberGenerator extends Remote{ - int get() throws RemoteException; -} diff --git a/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java b/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java deleted file mode 100644 index 04d90b2ff9..0000000000 --- a/rmi/src/org/baeldung/RandomNumberGeneratorEngine.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung; - -import java.rmi.RemoteException; - -public class RandomNumberGeneratorEngine implements RandomNumberGenerator { - @Override - public int get() throws RemoteException { - return (int) (100 * Math.random()); - } -} diff --git a/rmi/src/org/baeldung/Server.java b/rmi/src/org/baeldung/Server.java deleted file mode 100644 index 8e613cb6bb..0000000000 --- a/rmi/src/org/baeldung/Server.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung; - -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import java.rmi.server.UnicastRemoteObject; - -public class Server { - public static void main(String[] args) throws RemoteException { - System.setProperty("java.security.policy", "file:./server.policy"); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } - String name = "RandomNumberGenerator"; - RandomNumberGenerator randomNumberGenerator = new RandomNumberGeneratorEngine(); - RandomNumberGenerator stub = - (RandomNumberGenerator) UnicastRemoteObject.exportObject(randomNumberGenerator, 0); - Registry registry = LocateRegistry.getRegistry(); - registry.rebind(name, stub); - System.out.println("RandomNumberGenerator bound"); - } -} diff --git a/rsocket/README.md b/rsocket/README.md new file mode 100644 index 0000000000..fa232bc515 --- /dev/null +++ b/rsocket/README.md @@ -0,0 +1,3 @@ +Relevant articles + +- [Introduction to RSocket](https://www.baeldung.com/rsocket) diff --git a/rsocket/pom.xml b/rsocket/pom.xml new file mode 100644 index 0000000000..8b04a31583 --- /dev/null +++ b/rsocket/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + rsocket + 0.0.1-SNAPSHOT + rsocket + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + jar + + + + io.rsocket + rsocket-core + 0.11.13 + + + io.rsocket + rsocket-transport-netty + 0.11.13 + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-core + 1.3 + test + + + ch.qos.logback + logback-classic + 1.2.3 + + + ch.qos.logback + logback-core + 1.2.3 + + + org.slf4j + slf4j-api + 1.7.25 + + + \ No newline at end of file diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java new file mode 100644 index 0000000000..f35d337427 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ChannelClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import reactor.core.publisher.Flux; + +public class ChannelClient { + + private final RSocket socket; + private final GameController gameController; + + public ChannelClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + + this.gameController = new GameController("Client Player"); + } + + public void playGame() { + socket.requestChannel(Flux.from(gameController)) + .doOnNext(gameController::processPayload) + .blockLast(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java new file mode 100644 index 0000000000..a67078db06 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java @@ -0,0 +1,85 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class FireNForgetClient { + + private static final Logger LOG = LoggerFactory.getLogger(FireNForgetClient.class); + + private final RSocket socket; + private final List data; + + public FireNForgetClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + this.data = Collections.unmodifiableList(generateData()); + } + + /** + * Send binary velocity (float) every 50ms + */ + public void sendData() { + Flux.interval(Duration.ofMillis(50)) + .take(data.size()) + .map(this::createFloatPayload) + .flatMap(socket::fireAndForget) + .blockLast(); + } + + /** + * Create a binary payload containing a single float value + * + * @param index Index into the data list + * @return Payload ready to send to the server + */ + private Payload createFloatPayload(Long index) { + float velocity = data.get(index.intValue()); + ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity); + buffer.rewind(); + return DefaultPayload.create(buffer); + } + + /** + * Generate sample data + * + * @return List of random floats + */ + private List generateData() { + List dataList = new ArrayList<>(DATA_LENGTH); + float velocity = 0; + for (int i = 0; i < DATA_LENGTH; i++) { + velocity += Math.random(); + dataList.add(velocity); + } + return dataList; + } + + /** + * Get the data used for this client. + * + * @return list of data values + */ + public List getData() { + return data; + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java new file mode 100644 index 0000000000..fff196a580 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqResClient.java @@ -0,0 +1,32 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; + +public class ReqResClient { + + private final RSocket socket; + + public ReqResClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public String callBlocking(String string) { + return socket + .requestResponse(DefaultPayload.create(string)) + .map(Payload::getDataUtf8) + .onErrorReturn(ERROR_MSG) + .block(); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java new file mode 100644 index 0000000000..085f9874fa --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java @@ -0,0 +1,33 @@ +package com.baeldung.rsocket; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.RSocket; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.client.TcpClientTransport; +import io.rsocket.util.DefaultPayload; +import reactor.core.publisher.Flux; + +public class ReqStreamClient { + + private final RSocket socket; + + public ReqStreamClient() { + this.socket = RSocketFactory.connect() + .transport(TcpClientTransport.create("localhost", TCP_PORT)) + .start() + .block(); + } + + public Flux getDataStream() { + return socket + .requestStream(DefaultPayload.create(DATA_STREAM_NAME)) + .map(Payload::getData) + .map(buf -> buf.getFloat()) + .onErrorReturn(null); + } + + public void dispose() { + this.socket.dispose(); + } +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/Server.java b/rsocket/src/main/java/com/baeldung/rsocket/Server.java new file mode 100644 index 0000000000..42243da39f --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/Server.java @@ -0,0 +1,107 @@ +package com.baeldung.rsocket; + +import com.baeldung.rsocket.support.DataPublisher; +import static com.baeldung.rsocket.support.Constants.*; +import com.baeldung.rsocket.support.GameController; +import io.rsocket.AbstractRSocket; +import io.rsocket.Payload; +import io.rsocket.RSocketFactory; +import io.rsocket.transport.netty.server.TcpServerTransport; +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class Server { + + private static final Logger LOG = LoggerFactory.getLogger(Server.class); + + private final Disposable server; + private final DataPublisher dataPublisher = new DataPublisher(); + private final GameController gameController; + + public Server() { + this.server = RSocketFactory.receive() + .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl())) + .transport(TcpServerTransport.create("localhost", TCP_PORT)) + .start() + .doOnNext(x -> LOG.info("Server started")) + .subscribe(); + + this.gameController = new GameController("Server Player"); + } + + public void dispose() { + dataPublisher.complete(); + this.server.dispose(); + } + + /** + * RSocket implementation + */ + private class RSocketImpl extends AbstractRSocket { + + /** + * Handle Request/Response messages + * + * @param payload Message payload + * @return payload response + */ + @Override + public Mono requestResponse(Payload payload) { + try { + return Mono.just(payload); // reflect the payload back to the sender + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Fire-and-Forget messages + * + * @param payload Message payload + * @return nothing + */ + @Override + public Mono fireAndForget(Payload payload) { + try { + dataPublisher.publish(payload); // forward the payload + return Mono.empty(); + } catch (Exception x) { + return Mono.error(x); + } + } + + /** + * Handle Request/Stream messages. Each request returns a new stream. + * + * @param payload Payload that can be used to determine which stream to return + * @return Flux stream containing simulated measurement data + */ + @Override + public Flux requestStream(Payload payload) { + String streamName = payload.getDataUtf8(); + if (DATA_STREAM_NAME.equals(streamName)) { + return Flux.from(dataPublisher); + } + return Flux.error(new IllegalArgumentException(streamName)); + } + + /** + * Handle request for bidirectional channel + * + * @param payloads Stream of payloads delivered from the client + * @return + */ + @Override + public Flux requestChannel(Publisher payloads) { + Flux.from(payloads) + .subscribe(gameController::processPayload); + Flux channel = Flux.from(gameController); + return channel; + } + } + +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java new file mode 100644 index 0000000000..4ffc4f6483 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java @@ -0,0 +1,10 @@ +package com.baeldung.rsocket.support; + +public interface Constants { + + int TCP_PORT = 7101; + String ERROR_MSG = "error"; + int DATA_LENGTH = 30; + String DATA_STREAM_NAME = "data"; + int SHOT_COUNT = 10; +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java new file mode 100644 index 0000000000..3e74da8317 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java @@ -0,0 +1,31 @@ +package com.baeldung.rsocket.support; + +import io.rsocket.Payload; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; + +/** + * Simple PUblisher to provide async data to Flux stream + */ +public class DataPublisher implements Publisher { + + private Subscriber subscriber; + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + } + + public void publish(Payload payload) { + if (subscriber != null) { + subscriber.onNext(payload); + } + } + + public void complete() { + if (subscriber != null) { + subscriber.onComplete(); + } + } + +} diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java new file mode 100644 index 0000000000..bc1bc0f861 --- /dev/null +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/GameController.java @@ -0,0 +1,84 @@ +package com.baeldung.rsocket.support; + +import static com.baeldung.rsocket.support.Constants.*; +import io.rsocket.Payload; +import io.rsocket.util.DefaultPayload; +import java.util.List; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; + +public class GameController implements Publisher { + + private static final Logger LOG = LoggerFactory.getLogger(GameController.class); + + private final String playerName; + private final List shots; + private Subscriber subscriber; + private boolean truce = false; + + public GameController(String playerName) { + this.playerName = playerName; + this.shots = generateShotList(); + } + + /** + * Create a random list of time intervals, 0-1000ms + * + * @return List of time intervals + */ + private List generateShotList() { + return Flux.range(1, SHOT_COUNT) + .map(x -> (long) Math.ceil(Math.random() * 1000)) + .collectList() + .block(); + } + + @Override + public void subscribe(Subscriber subscriber) { + this.subscriber = subscriber; + fireAtWill(); + } + + /** + * Publish game events asynchronously + */ + private void fireAtWill() { + new Thread(() -> { + for (Long shotDelay : shots) { + try { Thread.sleep(shotDelay); } catch (Exception x) {} + if (truce) { + break; + } + LOG.info("{}: bang!", playerName); + subscriber.onNext(DefaultPayload.create("bang!")); + } + if (!truce) { + LOG.info("{}: I give up!", playerName); + subscriber.onNext(DefaultPayload.create("I give up")); + } + subscriber.onComplete(); + }).start(); + } + + /** + * Process events from the opponent + * + * @param payload Payload received from the rSocket + */ + public void processPayload(Payload payload) { + String message = payload.getDataUtf8(); + switch (message) { + case "bang!": + String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!"; + LOG.info("{}: {}", playerName, result); + break; + case "I give up": + truce = true; + LOG.info("{}: OK, truce", playerName); + break; + } + } +} diff --git a/mvn-wrapper/src/main/resources/logback.xml b/rsocket/src/main/resources/logback.xml similarity index 100% rename from mvn-wrapper/src/main/resources/logback.xml rename to rsocket/src/main/resources/logback.xml diff --git a/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java new file mode 100644 index 0000000000..afa3960eac --- /dev/null +++ b/rsocket/src/test/java/com/baeldung/rsocket/RSocketIntegrationTest.java @@ -0,0 +1,84 @@ +package com.baeldung.rsocket; + +import java.util.ArrayList; +import java.util.List; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Disposable; + +public class RSocketIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(RSocketIntegrationTest.class); + + private static Server server; + + public RSocketIntegrationTest() { + } + + @BeforeClass + public static void setUpClass() { + server = new Server(); + } + + @AfterClass + public static void tearDownClass() { + server.dispose(); + } + + @Test + public void whenSendingAString_thenRevceiveTheSameString() { + ReqResClient client = new ReqResClient(); + String string = "Hello RSocket"; + + assertEquals(string, client.callBlocking(string)); + + client.dispose(); + } + + @Test + public void whenSendingStream_thenReceiveTheSameStream() { + // create the client that pushes data to the server and start sending + FireNForgetClient fnfClient = new FireNForgetClient(); + // create a client to read a stream from the server and subscribe to events + ReqStreamClient streamClient = new ReqStreamClient(); + + // get the data that is used by the client + List data = fnfClient.getData(); + // create a place to count the results + List dataReceived = new ArrayList<>(); + + // assert that the data received is the same as the data sent + Disposable subscription = streamClient.getDataStream() + .index() + .subscribe( + tuple -> { + assertEquals("Wrong value", data.get(tuple.getT1().intValue()), tuple.getT2()); + dataReceived.add(tuple.getT2()); + }, + err -> LOG.error(err.getMessage()) + ); + + // start sending the data + fnfClient.sendData(); + + // wait a short time for the data to complete then dispose everything + try { Thread.sleep(500); } catch (Exception x) {} + subscription.dispose(); + fnfClient.dispose(); + + // verify the item count + assertEquals("Wrong data count received", data.size(), dataReceived.size()); + } + + @Test + public void whenRunningChannelGame_thenLogTheResults() { + ChannelClient client = new ChannelClient(); + client.playGame(); + client.dispose(); + } + +} diff --git a/rxjava-2/README.md b/rxjava-2/README.md index f9528bb1d5..d0bdeec684 100644 --- a/rxjava-2/README.md +++ b/rxjava-2/README.md @@ -6,3 +6,4 @@ - [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) - [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) - [Combining RxJava Completables](https://www.baeldung.com/rxjava-completable) +- [Converting Synchronous and Asynchronous APIs to Observables using RxJava2](https://www.baeldung.com/rxjava-apis-to-observables) diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index a18b096b6d..3038c20037 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -1,45 +1,53 @@ - - 4.0.0 + + 4.0.0 - rxjava-2 - 1.0-SNAPSHOT + rxjava-2 + 1.0-SNAPSHOT - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - io.reactivex.rxjava2 - rxjava - ${rx.java2.version} - - - com.jayway.awaitility - awaitility - ${awaitility.version} - - - org.assertj - assertj-core - ${assertj.version} - - - com.jakewharton.rxrelay2 - rxrelay - ${rxrelay.version} - - + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + + org.assertj + assertj-core + ${assertj.version} + + + com.jakewharton.rxrelay2 + rxrelay + ${rxrelay.version} + + + + com.github.akarnokd + rxjava2-extensions + ${rxjava2.ext.version} + + - - 3.8.0 - 2.2.2 - 1.7.0 - 2.0.0 - + + 3.8.0 + 2.2.2 + 1.7.0 + 2.0.0 + 0.20.4 + \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java new file mode 100644 index 0000000000..90f4fe94ae --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java @@ -0,0 +1,107 @@ +package com.baeldung.rxjava; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import hu.akarnokd.rxjava2.async.AsyncObservable; +import io.reactivex.Observable; + +public class AsyncAndSyncToObservableIntegrationTest { + + AtomicInteger counter = new AtomicInteger(); + Callable callable = () -> counter.incrementAndGet(); + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() { + + Observable source = Observable.fromCallable(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() { + + Observable source = AsyncObservable.start(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future future = executor.submit(callable); + Observable source = Observable.fromFuture(future); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + + executor.shutdown(); + } + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + + executor.shutdown(); + } + + /*Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { + List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); + ExecutorService exec = Executors.newSingleThreadExecutor(); + Callable> callable = () -> Observable.fromIterable(list); + Observable source = AsyncObservable.deferFuture(() -> exec.submit(callable)); + for (int i = 1; i < 4; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1, 2, 3); + } + + exec.shutdown(); + } + +} diff --git a/rxjava/pom.xml b/rxjava/pom.xml index b316001d87..596a5196da 100644 --- a/rxjava/pom.xml +++ b/rxjava/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - rxjava 1.0-SNAPSHOT - + rxjava + com.baeldung parent-java diff --git a/spring-4/README.md b/spring-4/README.md index 4600a603ef..402557eb41 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: -- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) - [A Guide to Flips for Spring](http://www.baeldung.com/flips-spring) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 5c723c6e29..aa73cf11ae 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -3,6 +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 spring-5-data-reactive + spring-5-data-reactive jar diff --git a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt index af29a429a4..5a59d11de0 100644 --- a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt +++ b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt @@ -2,8 +2,9 @@ package com.baeldung import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration -@SpringBootApplication +@SpringBootApplication(exclude = arrayOf(MongoReactiveDataAutoConfiguration::class)) class Application fun main(args: Array) { diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 8251467122..74a348dea6 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -4,10 +4,11 @@ import javax.servlet.Filter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@SpringBootApplication +@SpringBootApplication( exclude = SecurityAutoConfiguration.class) public class Spring5Application { public static void main(String[] args) { diff --git a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt index f95586af80..8904d8d805 100644 --- a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt +++ b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt @@ -2,8 +2,9 @@ package com.baeldung.springbootkotlin import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration -@SpringBootApplication(scanBasePackages = arrayOf("com.baeldung.springbootkotlin")) +@SpringBootApplication(scanBasePackages = arrayOf("com.baeldung.springbootkotlin"), exclude = arrayOf(SecurityAutoConfiguration::class)) class KotlinDemoApplication fun main(args: Array) { diff --git a/spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java b/spring-5-mvc/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from spring-5-mvc/src/test/kotlin/com/baeldung/LiveTest.java rename to spring-5-mvc/src/test/java/com/baeldung/LiveTest.java diff --git a/spring-5-reactive-oauth/README.md b/spring-5-reactive-oauth/README.md new file mode 100644 index 0000000000..0f27cf5d20 --- /dev/null +++ b/spring-5-reactive-oauth/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring Security OAuth Login with WebFlux](https://www.baeldung.com/spring-oauth-login-webflux) diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java index f07ddfb0f7..03943d436d 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/Spring5ReactiveApplication.java @@ -1,9 +1,7 @@ package com.baeldung.reactive.actuator; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; @SpringBootApplication public class Spring5ReactiveApplication{ diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java index ba913bc2d7..325923f577 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/security/SpringSecurity5Application.java @@ -8,6 +8,7 @@ import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; + import reactor.netty.DisposableServer; import reactor.netty.http.server.HttpServer; @@ -23,11 +24,14 @@ public class SpringSecurity5Application { } @Bean - public DisposableServer nettyContext(ApplicationContext context) { + public DisposableServer disposableServer(ApplicationContext context) { HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context) .build(); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); - return HttpServer.create().host("localhost").port(8080).handle(adapter).bind().block(); + HttpServer httpServer = HttpServer.create(); + httpServer.host("localhost"); + httpServer.port(8080); + return httpServer.handle(adapter).bindNow(); } } diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 267925b798..2a4ee017f4 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -16,3 +16,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Server-Sent Events in Spring](https://www.baeldung.com/spring-server-sent-events) - [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive) - [Validation for Functional Endpoints in Spring 5](https://www.baeldung.com/spring-functional-endpoints-validation) +- [Logging a Reactive Sequence](https://www.baeldung.com/spring-reactive-sequence-logging) +- [Testing Reactive Streams Using StepVerifier and TestPublisher](https://www.baeldung.com/reactive-streams-step-verifier-test-publisher) diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index e903b57c4e..63cc185afe 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -75,6 +75,11 @@ spring-boot-starter-test test + + org.springframework.security + spring-security-test + test + @@ -116,12 +121,6 @@ ${project-reactor-test} test - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - @@ -144,8 +143,7 @@ 1.0 1.0 4.1 - 3.1.6.RELEASE - 1.2.0 + 3.2.3.RELEASE diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java new file mode 100644 index 0000000000..486c5e77eb --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/ConsumerDebuggingApplication.java @@ -0,0 +1,33 @@ +package com.baeldung.debugging.consumer; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; + +import reactor.core.publisher.Hooks; + +@SpringBootApplication(exclude = MongoReactiveAutoConfiguration.class) +@EnableScheduling +public class ConsumerDebuggingApplication { + + public static void main(String[] args) { + Hooks.onOperatorDebug(); + SpringApplication app = new SpringApplication(ConsumerDebuggingApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); + app.run(args); + } + + @Bean + public SecurityWebFilterChain debuggingConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/chronjobs/ChronJobs.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/chronjobs/ChronJobs.java new file mode 100644 index 0000000000..bf96ab56d6 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/chronjobs/ChronJobs.java @@ -0,0 +1,154 @@ +package com.baeldung.debugging.consumer.chronjobs; + +import java.time.Duration; +import java.util.concurrent.ThreadLocalRandom; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; + +import com.baeldung.debugging.consumer.model.Foo; +import com.baeldung.debugging.consumer.model.FooDto; +import com.baeldung.debugging.consumer.service.FooService; + +import reactor.core.publisher.Flux; + +@Component +public class ChronJobs { + + private static Logger logger = LoggerFactory.getLogger(ChronJobs.class); + private WebClient client = WebClient.create("http://localhost:8081"); + + @Autowired + private FooService service; + + @Scheduled(fixedRate = 10000) + public void consumeInfiniteFlux() { + Flux fluxFoo = client.get() + .uri("/functional-reactive/periodic-foo") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(FooDto.class) + .delayElements(Duration.ofMillis(100)) + .map(dto -> { + logger.debug("process 1 with dto id {} name{}", dto.getId(), dto.getName()); + return new Foo(dto); + }); + Integer random = ThreadLocalRandom.current() + .nextInt(0, 3); + switch (random) { + case 0: + logger.info("process 1 with approach 1"); + service.processFoo(fluxFoo); + break; + case 1: + logger.info("process 1 with approach 1 EH"); + service.processUsingApproachOneWithErrorHandling(fluxFoo); + break; + default: + logger.info("process 1 with approach 2"); + service.processFooInAnotherScenario(fluxFoo); + break; + + } + } + + @Scheduled(fixedRate = 20000) + public void consumeFiniteFlux2() { + Flux fluxFoo = client.get() + .uri("/functional-reactive/periodic-foo-2") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(FooDto.class) + .delayElements(Duration.ofMillis(100)) + .map(dto -> { + logger.debug("process 2 with dto id {} name{}", dto.getId(), dto.getName()); + return new Foo(dto); + }); + Integer random = ThreadLocalRandom.current() + .nextInt(0, 3); + switch (random) { + case 0: + logger.info("process 2 with approach 1"); + service.processFoo(fluxFoo); + break; + case 1: + logger.info("process 2 with approach 1 EH"); + service.processUsingApproachOneWithErrorHandling(fluxFoo); + break; + default: + logger.info("process 2 with approach 2"); + service.processFooInAnotherScenario(fluxFoo); + break; + + } + } + + @Scheduled(fixedRate = 20000) + public void consumeFiniteFlux3() { + Flux fluxFoo = client.get() + .uri("/functional-reactive/periodic-foo-2") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(FooDto.class) + .delayElements(Duration.ofMillis(100)) + .map(dto -> { + logger.debug("process 3 with dto id {} name{}", dto.getId(), dto.getName()); + return new Foo(dto); + }); + logger.info("process 3 with approach 3"); + service.processUsingApproachThree(fluxFoo); + } + + @Scheduled(fixedRate = 20000) + public void consumeFiniteFluxWithCheckpoint4() { + Flux fluxFoo = client.get() + .uri("/functional-reactive/periodic-foo-2") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(FooDto.class) + .delayElements(Duration.ofMillis(100)) + .map(dto -> { + logger.debug("process 4 with dto id {} name{}", dto.getId(), dto.getName()); + return new Foo(dto); + }); + logger.info("process 4 with approach 4"); + service.processUsingApproachFourWithCheckpoint(fluxFoo); + } + + @Scheduled(fixedRate = 20000) + public void consumeFiniteFluxWitParallelScheduler() { + Flux fluxFoo = client.get() + .uri("/functional-reactive/periodic-foo-2") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(FooDto.class) + .delayElements(Duration.ofMillis(100)) + .map(dto -> { + logger.debug("process 5-parallel with dto id {} name{}", dto.getId(), dto.getName()); + return new Foo(dto); + }); + logger.info("process 5-parallel with approach 5-parallel"); + service.processUsingApproachFivePublishingToDifferentParallelThreads(fluxFoo); + } + + @Scheduled(fixedRate = 20000) + public void consumeFiniteFluxWithSingleSchedulers() { + Flux fluxFoo = client.get() + .uri("/functional-reactive/periodic-foo-2") + .accept(MediaType.TEXT_EVENT_STREAM) + .retrieve() + .bodyToFlux(FooDto.class) + .delayElements(Duration.ofMillis(100)) + .map(dto -> { + logger.debug("process 5-single with dto id {} name{}", dto.getId(), dto.getName()); + return new Foo(dto); + }); + logger.info("process 5-single with approach 5-single"); + service.processUsingApproachFivePublishingToDifferentSingleThreads(fluxFoo); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/controllers/ReactiveConfigsToggleRestController.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/controllers/ReactiveConfigsToggleRestController.java new file mode 100644 index 0000000000..3dcdc6c7c0 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/controllers/ReactiveConfigsToggleRestController.java @@ -0,0 +1,23 @@ +package com.baeldung.debugging.consumer.controllers; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Hooks; + +@RestController +public class ReactiveConfigsToggleRestController { + + @GetMapping("/debug-hook-on") + public String setReactiveDebugOn() { + Hooks.onOperatorDebug(); + return "DEBUG HOOK ON"; + } + + @GetMapping("/debug-hook-off") + public String setReactiveDebugOff() { + Hooks.resetOnOperatorDebug(); + return "DEBUG HOOK OFF"; + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/model/Foo.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/model/Foo.java new file mode 100644 index 0000000000..ac5093c261 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/model/Foo.java @@ -0,0 +1,31 @@ +package com.baeldung.debugging.consumer.model; + +import java.util.concurrent.ThreadLocalRandom; + +import org.springframework.data.annotation.Id; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class Foo { + + @Id + private Integer id; + private String formattedName; + private Integer quantity; + + public Foo(FooDto dto) { + this.id = (ThreadLocalRandom.current() + .nextInt(0, 100) == 0) ? null : dto.getId(); + this.formattedName = dto.getName(); + this.quantity = ThreadLocalRandom.current() + .nextInt(0, 10); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/model/FooDto.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/model/FooDto.java new file mode 100644 index 0000000000..33f19c4e60 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/model/FooDto.java @@ -0,0 +1,16 @@ +package com.baeldung.debugging.consumer.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class FooDto { + + private Integer id; + private String name; +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooNameHelper.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooNameHelper.java new file mode 100644 index 0000000000..772b360437 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooNameHelper.java @@ -0,0 +1,45 @@ +package com.baeldung.debugging.consumer.service; + +import java.util.concurrent.ThreadLocalRandom; + +import com.baeldung.debugging.consumer.model.Foo; + +import reactor.core.publisher.Flux; + +public class FooNameHelper { + + public static Flux concatAndSubstringFooName(Flux flux) { + flux = concatFooName(flux); + flux = substringFooName(flux); + return flux; + } + + public static Flux concatFooName(Flux flux) { + flux = flux.map(foo -> { + String processedName = null; + Integer random = ThreadLocalRandom.current() + .nextInt(0, 80); + processedName = (random != 0) ? foo.getFormattedName() : foo.getFormattedName() + "-bael"; + foo.setFormattedName(processedName); + return foo; + }); + return flux; + } + + public static Flux substringFooName(Flux flux) { + return flux.map(foo -> { + String processedName; + Integer random = ThreadLocalRandom.current() + .nextInt(0, 100); + + processedName = (random == 0) ? foo.getFormattedName() + .substring(10, 15) + : foo.getFormattedName() + .substring(0, 5); + + foo.setFormattedName(processedName); + return foo; + }); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooQuantityHelper.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooQuantityHelper.java new file mode 100644 index 0000000000..615239313d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooQuantityHelper.java @@ -0,0 +1,31 @@ +package com.baeldung.debugging.consumer.service; + +import java.util.concurrent.ThreadLocalRandom; + +import com.baeldung.debugging.consumer.model.Foo; + +import reactor.core.publisher.Flux; + +public class FooQuantityHelper { + + public static Flux processFooReducingQuantity(Flux flux) { + flux = flux.map(foo -> { + Integer result; + Integer random = ThreadLocalRandom.current() + .nextInt(0, 90); + result = (random == 0) ? result = 0 : foo.getQuantity() + 2; + foo.setQuantity(result); + return foo; + }); + return divideFooQuantity(flux); + } + + public static Flux divideFooQuantity(Flux flux) { + return flux.map(foo -> { + Integer result = Math.round(5 / foo.getQuantity()); + foo.setQuantity(result); + return foo; + }); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooReporter.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooReporter.java new file mode 100644 index 0000000000..f53cd238e0 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooReporter.java @@ -0,0 +1,26 @@ +package com.baeldung.debugging.consumer.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.debugging.consumer.model.Foo; + +import reactor.core.publisher.Flux; + +public class FooReporter { + + private static Logger logger = LoggerFactory.getLogger(FooReporter.class); + + public static Flux reportResult(Flux input, String approach) { + return input.map(foo -> { + if (foo.getId() == null) + throw new IllegalArgumentException("Null id is not valid!"); + logger.info("Reporting for approach {}: Foo with id '{}' name '{}' and quantity '{}'", approach, foo.getId(), foo.getFormattedName(), foo.getQuantity()); + return foo; + }); + } + + public static Flux reportResult(Flux input) { + return reportResult(input, "default"); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooService.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooService.java new file mode 100644 index 0000000000..438f6d473c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/consumer/service/FooService.java @@ -0,0 +1,120 @@ +package com.baeldung.debugging.consumer.service; + +import static com.baeldung.debugging.consumer.service.FooNameHelper.concatAndSubstringFooName; +import static com.baeldung.debugging.consumer.service.FooNameHelper.substringFooName; +import static com.baeldung.debugging.consumer.service.FooQuantityHelper.divideFooQuantity; +import static com.baeldung.debugging.consumer.service.FooQuantityHelper.processFooReducingQuantity; +import static com.baeldung.debugging.consumer.service.FooReporter.reportResult; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import com.baeldung.debugging.consumer.model.Foo; + +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; + +@Component +public class FooService { + + private static Logger logger = LoggerFactory.getLogger(FooService.class); + + public void processFoo(Flux flux) { + flux = FooNameHelper.concatFooName(flux); + flux = FooNameHelper.substringFooName(flux); + flux = flux.log(); + flux = FooReporter.reportResult(flux); + flux = flux.doOnError(error -> { + logger.error("The following error happened on processFoo method!", error); + }); + flux.subscribe(); + } + + public void processFooInAnotherScenario(Flux flux) { + flux = FooNameHelper.substringFooName(flux); + flux = FooQuantityHelper.divideFooQuantity(flux); + flux.subscribe(); + } + + public void processUsingApproachOneWithErrorHandling(Flux flux) { + logger.info("starting approach one w error handling!"); + flux = concatAndSubstringFooName(flux); + flux = concatAndSubstringFooName(flux); + flux = substringFooName(flux); + flux = processFooReducingQuantity(flux); + flux = processFooReducingQuantity(flux); + flux = processFooReducingQuantity(flux); + flux = reportResult(flux, "ONE w/ EH"); + flux = flux.doOnError(error -> { + logger.error("Approach 1 with Error Handling failed!", error); + }); + flux.subscribe(); + } + + public void processUsingApproachThree(Flux flux) { + logger.info("starting approach three!"); + flux = concatAndSubstringFooName(flux); + flux = reportResult(flux, "THREE"); + flux = flux.doOnError(error -> { + logger.error("Approach 3 failed!", error); + }); + flux.subscribe(); + } + + public void processUsingApproachFourWithCheckpoint(Flux flux) { + logger.info("starting approach four!"); + flux = concatAndSubstringFooName(flux); + flux = flux.checkpoint("CHECKPOINT 1"); + flux = concatAndSubstringFooName(flux); + flux = divideFooQuantity(flux); + flux = flux.checkpoint("CHECKPOINT 2", true); + flux = reportResult(flux, "FOUR"); + flux = concatAndSubstringFooName(flux).doOnError(error -> { + logger.error("Approach 4 failed!", error); + }); + flux.subscribe(); + } + + public void processUsingApproachFourWithInitialCheckpoint(Flux flux) { + logger.info("starting approach four!"); + flux = concatAndSubstringFooName(flux); + flux = flux.checkpoint("CHECKPOINT 1", true); + flux = concatAndSubstringFooName(flux); + flux = divideFooQuantity(flux); + flux = reportResult(flux, "FOUR"); + flux = flux.doOnError(error -> { + logger.error("Approach 4-2 failed!", error); + }); + flux.subscribe(); + } + + public void processUsingApproachFivePublishingToDifferentParallelThreads(Flux flux) { + logger.info("starting approach five-parallel!"); + flux = concatAndSubstringFooName(flux).publishOn(Schedulers.newParallel("five-parallel-foo")) + .log(); + flux = concatAndSubstringFooName(flux); + flux = divideFooQuantity(flux); + flux = reportResult(flux, "FIVE-PARALLEL").publishOn(Schedulers.newSingle("five-parallel-bar")); + flux = concatAndSubstringFooName(flux).doOnError(error -> { + logger.error("Approach 5-parallel failed!", error); + }); + flux.subscribeOn(Schedulers.newParallel("five-parallel-starter")) + .subscribe(); + } + + public void processUsingApproachFivePublishingToDifferentSingleThreads(Flux flux) { + logger.info("starting approach five-single!"); + flux = flux.log() + .subscribeOn(Schedulers.newSingle("five-single-starter")); + flux = concatAndSubstringFooName(flux).publishOn(Schedulers.newSingle("five-single-foo")); + flux = concatAndSubstringFooName(flux); + flux = divideFooQuantity(flux); + flux = reportResult(flux, "FIVE-SINGLE").publishOn(Schedulers.newSingle("five-single-bar")); + flux = concatAndSubstringFooName(flux).doOnError(error -> { + logger.error("Approach 5-single failed!", error); + }); + flux.subscribe(); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java new file mode 100644 index 0000000000..4fdc1dd137 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/ServerDebuggingApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.debugging.server; + +import java.util.Collections; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.web.reactive.config.EnableWebFlux; + +@EnableWebFlux +@SpringBootApplication +public class ServerDebuggingApplication { + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(ServerDebuggingApplication.class); + app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); + app.run(args); + } + + @Bean + public SecurityWebFilterChain debuggingServerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/handlers/ServerHandler.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/handlers/ServerHandler.java new file mode 100644 index 0000000000..759cd9b01d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/handlers/ServerHandler.java @@ -0,0 +1,47 @@ +package com.baeldung.debugging.server.handlers; + +import java.time.Duration; +import java.util.concurrent.ThreadLocalRandom; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.debugging.server.model.Foo; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Component +public class ServerHandler { + + private static Logger logger = LoggerFactory.getLogger(ServerHandler.class); + + public Mono useHandler(final ServerRequest request) { + // there are chances that something goes wrong here... + return ServerResponse.ok() + .contentType(MediaType.TEXT_EVENT_STREAM) + .body(Flux.interval(Duration.ofSeconds(1)) + .map(sequence -> { + logger.info("retrieving Foo. Sequence: {}", sequence); + if (ThreadLocalRandom.current() + .nextInt(0, 50) == 1) { + throw new RuntimeException("There was an error retrieving the Foo!"); + } + return new Foo(sequence, "name" + sequence); + + }), Foo.class); + } + + public Mono useHandlerFinite(final ServerRequest request) { + return ServerResponse.ok() + .contentType(MediaType.TEXT_EVENT_STREAM) + .body(Flux.range(0, 50) + .map(sequence -> { + return new Foo(new Long(sequence), "theFooNameNumber" + sequence); + }), Foo.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/model/Foo.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/model/Foo.java new file mode 100644 index 0000000000..a60e468e7f --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/model/Foo.java @@ -0,0 +1,16 @@ +package com.baeldung.debugging.server.model; + +import org.springframework.data.annotation.Id; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class Foo { + + @Id + private Long id; + private String name; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/server/routers/ServerRouter.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/routers/ServerRouter.java new file mode 100644 index 0000000000..6378b2213d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/server/routers/ServerRouter.java @@ -0,0 +1,22 @@ +package com.baeldung.debugging.server.routers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.debugging.server.handlers.ServerHandler; + +@Configuration +public class ServerRouter { + + @Bean + public RouterFunction responseRoute(@Autowired ServerHandler handler) { + return RouterFunctions.route(RequestPredicates.GET("/functional-reactive/periodic-foo"), handler::useHandler) + .andRoute(RequestPredicates.GET("/functional-reactive/periodic-foo-2"), handler::useHandlerFinite); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index a1d5d87d5c..9cbc1b7669 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -17,8 +17,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.web.reactive.function.server.RouterFunction; @@ -40,11 +38,14 @@ public class FunctionalSpringBootApplication { private RouterFunction routingFunction() { FormHandler formHandler = new FormHandler(); - RouterFunction restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) - .doOnNext(actors::add) - .then(ok().build())); + RouterFunction restfulRouter = route(GET("/"), + serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), + serverRequest -> serverRequest.bodyToMono(Actor.class) + .doOnNext(actors::add) + .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) + .andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter) @@ -68,5 +69,4 @@ public class FunctionalSpringBootApplication { public static void main(String[] args) { SpringApplication.run(FunctionalSpringBootApplication.class, args); } - } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java index 1656f70221..a8cd18c470 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -1,9 +1,7 @@ package com.baeldung.reactive; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; @SpringBootApplication public class Spring5ReactiveApplication{ diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java index d990928abe..69ae24b849 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java @@ -4,6 +4,9 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication public class CorsOnAnnotatedElementsApplication { @@ -14,4 +17,9 @@ public class CorsOnAnnotatedElementsApplication { app.run(args); } + @Bean + public SecurityWebFilterChain corsAnnotatedSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java index 8228944569..a70f937980 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java @@ -8,6 +8,9 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -22,4 +25,9 @@ public class CorsGlobalConfigApplication { app.run(args); } + @Bean + public SecurityWebFilterChain corsGlobalSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java similarity index 93% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java index e6e32d7cc8..d2b7af29a6 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/FunctionalHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java @@ -7,7 +7,7 @@ import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; @Component -public class FunctionalHandler { +public class CorsGlobalFunctionalHandler { public Mono useHandler(final ServerRequest request) { final String responseMessage = "CORS GLOBAL CONFIG IS NOT EFFECTIVE ON FUNCTIONAL ENDPOINTS!!!"; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java index 19621a9e97..0a520828b9 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java @@ -8,13 +8,13 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; -import com.baeldung.reactive.cors.global.functional.handlers.FunctionalHandler; +import com.baeldung.reactive.cors.global.functional.handlers.CorsGlobalFunctionalHandler; @Configuration public class CorsRouterFunctions { @Bean - public RouterFunction responseHeaderRoute(@Autowired FunctionalHandler handler) { + public RouterFunction corsGlobalRouter(@Autowired CorsGlobalFunctionalHandler handler) { return RouterFunctions.route(RequestPredicates.PUT("/global-config-on-functional/cors-disabled-functional-endpoint"), handler::useHandler); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java index 38140c0d71..7792975768 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java @@ -8,6 +8,9 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, @@ -21,5 +24,11 @@ public class CorsWebFilterApplication { app.setDefaultProperties(Collections.singletonMap("server.port", "8083")); app.run(args); } + + @Bean + public SecurityWebFilterChain corsWebfilterSpringSecurityFilterChain(ServerHttpSecurity http) { + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java index a3905bb79f..6056b9bf5a 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java @@ -14,7 +14,7 @@ import com.baeldung.reactive.cors.webfilter.functional.handlers.CorsWithWebFilte public class CorsWithWebFilterRouterFunctions { @Bean - public RouterFunction responseHeaderRoute(@Autowired CorsWithWebFilterHandler handler) { + public RouterFunction corsWebfilterRouter(@Autowired CorsWithWebFilterHandler handler) { return RouterFunctions.route(RequestPredicates.PUT("/web-filter-on-functional/functional-endpoint"), handler::useHandler); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java index 3997607ef0..d8edaf7fd5 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -4,9 +4,13 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; -@SpringBootApplication +@SpringBootApplication(exclude = { RedisReactiveAutoConfiguration.class }) @EnableAsync public class ConsumerSSEApplication { @@ -15,5 +19,13 @@ public class ConsumerSSEApplication { app.setDefaultProperties(Collections.singletonMap("server.port", "8082")); app.run(args); } + + @Bean + public SecurityWebFilterChain sseConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java index 2750e6616d..c040b83da0 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java @@ -4,14 +4,26 @@ import java.util.Collections; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; -@SpringBootApplication +@SpringBootApplication(exclude = { RedisReactiveAutoConfiguration.class }) public class ServerSSEApplication { - + public static void main(String[] args) { SpringApplication app = new SpringApplication(ServerSSEApplication.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8081")); app.run(args); } + @Bean + public SecurityWebFilterChain sseServerSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } + } diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java index e548e33c85..4cbb65dc60 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java @@ -2,6 +2,9 @@ package com.baeldung.validations.functional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; @SpringBootApplication public class FunctionalValidationsApplication { @@ -9,4 +12,13 @@ public class FunctionalValidationsApplication { public static void main(String[] args) { SpringApplication.run(FunctionalValidationsApplication.class, args); } + + @Bean + public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + http.csrf().disable(); + return http.build(); + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java index efbdbe3f99..29582a0b0f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java @@ -17,7 +17,7 @@ import com.baeldung.validations.functional.handlers.impl.OtherEntityValidationHa public class ValidationsRouters { @Bean - public RouterFunction responseHeaderRoute(@Autowired CustomRequestEntityValidationHandler dryHandler, + public RouterFunction validationsRouter(@Autowired CustomRequestEntityValidationHandler dryHandler, @Autowired FunctionalHandler complexHandler, @Autowired OtherEntityValidationHandler otherHandler, @Autowired AnnotatedRequestEntityValidationHandler annotatedEntityHandler) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/webflux/logging/WebFluxLoggingExample.java b/spring-5-reactive/src/main/java/com/baeldung/webflux/logging/WebFluxLoggingExample.java new file mode 100644 index 0000000000..c4881b2296 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/webflux/logging/WebFluxLoggingExample.java @@ -0,0 +1,21 @@ +package com.baeldung.webflux.logging; + +import reactor.core.publisher.Flux; + +public class WebFluxLoggingExample { + + public static void main(String[] args) { + Flux reactiveStream = Flux.range(1, 5).log(); + + reactiveStream.subscribe(); + + reactiveStream = Flux.range(1, 5).log().take(3); + + reactiveStream.subscribe(); + + reactiveStream = Flux.range(1, 5).take(3).log(); + + reactiveStream.subscribe(); + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java index 452bcac8ab..61927e47ab 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websession/configuration/WebFluxSecurityConfig.java @@ -34,9 +34,8 @@ public class WebFluxSecurityConfig { } @Bean - public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - .authorizeExchange() + public SecurityWebFilterChain webSessionSpringSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() .anyExchange().authenticated() .and() .httpBasic() @@ -44,8 +43,7 @@ public class WebFluxSecurityConfig { .and() .formLogin(); - http - .csrf().disable(); + http.csrf().disable(); return http.build(); diff --git a/spring-5-reactive/src/main/resources/application.properties b/spring-5-reactive/src/main/resources/application.properties index 92f3116f84..4b49e8e8a2 100644 --- a/spring-5-reactive/src/main/resources/application.properties +++ b/spring-5-reactive/src/main/resources/application.properties @@ -1,2 +1 @@ -logging.level.root=INFO - +logging.level.root=INFO \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java new file mode 100644 index 0000000000..b7ed031ec7 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceIntegrationTest.java @@ -0,0 +1,65 @@ +package com.baeldung.debugging.consumer; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.baeldung.debugging.consumer.model.Foo; +import com.baeldung.debugging.consumer.service.FooService; +import com.baeldung.debugging.consumer.utils.ListAppender; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.IThrowableProxy; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Hooks; + +public class ConsumerFooServiceIntegrationTest { + + FooService service = new FooService(); + + @BeforeEach + public void clearLogList() { + Hooks.onOperatorDebug(); + ListAppender.clearEventList(); + } + + @Test + public void givenFooWithNullId_whenProcessFoo_thenLogsWithDebugTrace() { + Foo one = new Foo(1, "nameverylong", 8); + Foo two = new Foo(null, "nameverylong", 4); + Flux flux = Flux.just(one, two); + + service.processFoo(flux); + + Collection allLoggedEntries = ListAppender.getEvents() + .stream() + .map(ILoggingEvent::getFormattedMessage) + .collect(Collectors.toList()); + + Collection allSuppressedEntries = ListAppender.getEvents() + .stream() + .map(ILoggingEvent::getThrowableProxy) + .flatMap(t -> { + return Optional.ofNullable(t) + .map(IThrowableProxy::getSuppressed) + .map(Arrays::stream) + .orElse(Stream.empty()); + }) + .map(IThrowableProxy::getMessage) + .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)")); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java new file mode 100644 index 0000000000..af9bdfbc9b --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/ConsumerFooServiceLiveTest.java @@ -0,0 +1,49 @@ +package com.baeldung.debugging.consumer; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +import com.baeldung.debugging.consumer.service.FooService; + +public class ConsumerFooServiceLiveTest { + + FooService service = new FooService(); + + private static final String BASE_URL = "http://localhost:8082"; + private static final String DEBUG_HOOK_ON = BASE_URL + "/debug-hook-on"; + private static final String DEBUG_HOOK_OFF = BASE_URL + "/debug-hook-off"; + + private static WebTestClient client; + + @BeforeAll + public static void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void whenRequestingDebugHookOn_thenObtainExpectedMessage() { + ResponseSpec response = client.get() + .uri(DEBUG_HOOK_ON) + .exchange(); + response.expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("DEBUG HOOK ON"); + } + + @Test + public void whenRequestingDebugHookOff_thenObtainExpectedMessage() { + ResponseSpec response = client.get() + .uri(DEBUG_HOOK_OFF) + .exchange(); + response.expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("DEBUG HOOK OFF"); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/utils/ListAppender.java b/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/utils/ListAppender.java new file mode 100644 index 0000000000..c8c1c110bb --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/debugging/consumer/utils/ListAppender.java @@ -0,0 +1,25 @@ +package com.baeldung.debugging.consumer.utils; + +import java.util.ArrayList; +import java.util.List; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; + +public class ListAppender extends AppenderBase { + + static private List events = new ArrayList<>(); + + @Override + protected void append(ILoggingEvent eventObject) { + events.add(eventObject); + } + + public static List getEvents() { + return events; + } + + public static void clearEventList() { + events.clear(); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index 4dea2a05cf..1256d5f129 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java index 384600994e..b8dd9c9509 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/Spring5ReactiveServerClientIntegrationTest.java @@ -1,6 +1,10 @@ package com.baeldung.reactive; -import com.baeldung.web.reactive.Task; +import static org.springframework.web.reactive.function.server.RequestPredicates.GET; +import static org.springframework.web.reactive.function.server.RequestPredicates.POST; + +import java.time.Duration; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.springframework.http.server.reactive.HttpHandler; @@ -8,22 +12,22 @@ import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.web.reactive.Task; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.netty.DisposableServer; import reactor.netty.http.server.HttpServer; -import java.time.Duration; - -import static org.springframework.web.reactive.function.server.RequestPredicates.GET; -import static org.springframework.web.reactive.function.server.RequestPredicates.POST; - public class Spring5ReactiveServerClientIntegrationTest { - private static DisposableServer nettyServer; + private static DisposableServer disposableServer; @BeforeAll public static void setUp() throws Exception { - HttpServer server = HttpServer.create().host("localhost").port(8080); + HttpServer server = HttpServer.create() + .host("localhost") + .port(8080); RouterFunction route = RouterFunctions.route(POST("/task/process"), request -> ServerResponse.ok() .body(request.bodyToFlux(Task.class) .map(ll -> new Task("TaskName", 1)), Task.class)) @@ -31,12 +35,13 @@ public class Spring5ReactiveServerClientIntegrationTest { .body(Mono.just("server is alive"), String.class))); HttpHandler httpHandler = RouterFunctions.toHttpHandler(route); ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); - nettyServer = server.handle(adapter).bind().block(); + disposableServer = server.handle(adapter) + .bindNow(); } @AfterAll public static void shutDown() { - nettyServer.dispose(); + disposableServer.disposeNow(); } // @Test diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java index 0043d62e5a..e6847e63da 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnAnnotatedElementsLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java index 39927af4c3..008f1a16f2 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnGlobalConfigLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java index e5a3c8a99a..f8a4f34e29 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.cors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnWebFilterLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java index bea2eaa75f..10cfaffce4 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java @@ -8,11 +8,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +@WithMockUser public class ErrorHandlingIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java index bb2408ea79..fbf46a93cc 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class PlayerHandlerIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java index e7d289e5c4..22991b298f 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class UserControllerIntegrationTest { @Autowired diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java index db563e27d1..927c52e7e6 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/responseheaders/ResponseHeaderLiveTest.java @@ -2,13 +2,10 @@ package com.baeldung.reactive.responseheaders; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class ResponseHeaderLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java index 53f4a3b1bb..547cd99034 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java @@ -3,14 +3,13 @@ package com.baeldung.reactive.serversentsevents; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; -@RunWith(JUnitPlatform.class) @SpringBootTest +@WithMockUser public class ServiceSentEventLiveTest { private WebTestClient client = WebTestClient.bindToServer() diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java index 9f31608ff7..d4c1cfe4c8 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -4,6 +4,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @@ -12,6 +13,7 @@ import com.baeldung.reactive.controller.PathPatternController; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5ReactiveApplication.class) +@WithMockUser public class PathPatternsUsingHandlerMethodIntegrationTest { private static WebTestClient client; diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java new file mode 100644 index 0000000000..17fea6b50b --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.time.Duration; + +public class PostExecutionUnitTest { + + Flux source = Flux.create(emitter -> { + emitter.next(1); + emitter.next(2); + emitter.next(3); + emitter.complete(); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + emitter.next(4); + }).filter(number -> number % 2 == 0); + + @Test + public void droppedElements() { + StepVerifier.create(source) + .expectNext(2) + .expectComplete() + .verifyThenAssertThat() + .hasDropped(4) + .tookLessThan(Duration.ofMillis(1050)); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java new file mode 100644 index 0000000000..c7196d6b6c --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +public class StepByStepUnitTest { + + Flux source = Flux.just("John", "Monica", "Mark", "Cloe", "Frank", "Casper", "Olivia", "Emily", "Cate") + .filter(name -> name.length() == 4) + .map(String::toUpperCase); + + @Test + public void shouldReturnForLettersUpperCaseStrings() { + StepVerifier + .create(source) + .expectNext("JOHN") + .expectNextMatches(name -> name.startsWith("MA")) + .expectNext("CLOE", "CATE") + .expectComplete() + .verify(); + } + + @Test + public void shouldThrowExceptionAfterFourElements() { + Flux error = source.concatWith( + Mono.error(new IllegalArgumentException("Our message")) + ); + + StepVerifier + .create(error) + .expectNextCount(4) + .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && + throwable.getMessage().equals("Our message") + ).verify(); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java new file mode 100644 index 0000000000..fb65e2d315 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; +import reactor.test.publisher.TestPublisher; + +public class TestingTestPublisherUnitTest { + + @Test + public void testPublisher() { + TestPublisher + .create() + .next("First", "Second", "Third") + .error(new RuntimeException("Message")); + } + + @Test + public void nonCompliant() { + TestPublisher + .createNoncompliant(TestPublisher.Violation.ALLOW_NULL) + .emit("1", "2", null, "3"); + } + + @Test + public void testPublisherInAction() { + final TestPublisher testPublisher = TestPublisher.create(); + + UppercaseConverter uppercaseConverter = new UppercaseConverter(testPublisher.flux()); + + StepVerifier.create(uppercaseConverter.getUpperCase()) + .then(() -> testPublisher.emit("aA", "bb", "ccc")) + .expectNext("AA", "BB", "CCC") + .verifyComplete(); + } + +} + +class UppercaseConverter { + private final Flux source; + + UppercaseConverter(Flux source) { + this.source = source; + } + + Flux getUpperCase() { + return source + .map(String::toUpperCase); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java new file mode 100644 index 0000000000..54e5e7882a --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.time.Duration; + +public class TimeBasedUnitTest { + + @Test + public void simpleExample() { + StepVerifier + .withVirtualTime(() -> Flux.interval(Duration.ofSeconds(1)).take(2)) + .expectSubscription() + .expectNoEvent(Duration.ofSeconds(1)) + .expectNext(0L) + .thenAwait(Duration.ofSeconds(1)) + .expectNext(1L) + .verifyComplete(); + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java index 5fe764bf8f..73968cdf05 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java @@ -2,9 +2,7 @@ package com.baeldung.validations.functional; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; @@ -13,7 +11,6 @@ import com.baeldung.validations.functional.model.CustomRequestEntity; import reactor.core.publisher.Mono; -@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class FunctionalEndpointValidationsLiveTest { diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java index 08bd883b0b..2e37f2ffbd 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.web.client; -import com.baeldung.reactive.Spring5ReactiveApplication; 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.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.server.RequestPredicates; @@ -12,10 +12,14 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.WebHandler; + +import com.baeldung.reactive.Spring5ReactiveApplication; + import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5ReactiveApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@WithMockUser public class WebTestClientIntegrationTest { @LocalServerPort diff --git a/spring-5-reactive/src/test/resources/logback-test.xml b/spring-5-reactive/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..514029e402 --- /dev/null +++ b/spring-5-reactive/src/test/resources/logback-test.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-5-security-oauth/README.md b/spring-5-security-oauth/README.md new file mode 100644 index 0000000000..f13925992b --- /dev/null +++ b/spring-5-security-oauth/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Spring Security 5 -OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) +- [Extracting Principal and Authorities using Spring Security OAuth](https://www.baeldung.com/spring-security-oauth-principal-authorities-extractor) diff --git a/spring-5-security-oauth/pom.xml b/spring-5-security-oauth/pom.xml new file mode 100644 index 0000000000..59150a153f --- /dev/null +++ b/spring-5-security-oauth/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + com.baeldung + spring-5-security-oauth + 0.0.1-SNAPSHOT + jar + spring-5-security-oauth + spring 5 security oauth sample project + + + 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.thymeleaf.extras + thymeleaf-extras-springsecurity5 + + + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + ${oauth-auto.version} + + + org.springframework.security + spring-security-oauth2-client + + + org.springframework.security + spring-security-oauth2-jose + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + 2.1.0.RELEASE + 2.1.0.RELEASE + com.baeldung.oauth2.SpringOAuthApplication + + + diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/CustomRequestSecurityConfig.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/CustomRequestSecurityConfig.java new file mode 100644 index 0000000000..2aba5a82ac --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/CustomRequestSecurityConfig.java @@ -0,0 +1,118 @@ +package com.baeldung.oauth2; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.http.converter.FormHttpMessageConverter; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.oauth2.client.CommonOAuth2Provider; +import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; +import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; +import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository; +import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; +import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +import com.baeldung.oauth2request.CustomAuthorizationRequestResolver; +import com.baeldung.oauth2request.CustomRequestEntityConverter; +import com.baeldung.oauth2request.CustomTokenResponseConverter; + +//@Configuration +@PropertySource("application-oauth2.properties") +public class CustomRequestSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/oauth_login", "/loginFailure", "/") + .permitAll() + .anyRequest() + .authenticated() + .and() + .oauth2Login() + .loginPage("/oauth_login") + .authorizationEndpoint() + .authorizationRequestResolver( new CustomAuthorizationRequestResolver(clientRegistrationRepository(),"/oauth2/authorize-client")) + + .baseUri("/oauth2/authorize-client") + .authorizationRequestRepository(authorizationRequestRepository()) + .and() + .tokenEndpoint() + .accessTokenResponseClient(accessTokenResponseClient()) + .and() + .defaultSuccessUrl("/loginSuccess") + .failureUrl("/loginFailure"); + } + + @Bean + public AuthorizationRequestRepository authorizationRequestRepository() { + return new HttpSessionOAuth2AuthorizationRequestRepository(); + } + + @Bean + public OAuth2AccessTokenResponseClient accessTokenResponseClient() { + DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient(); + accessTokenResponseClient.setRequestEntityConverter(new CustomRequestEntityConverter()); + + OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); + tokenResponseHttpMessageConverter.setTokenResponseConverter(new CustomTokenResponseConverter()); + RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), tokenResponseHttpMessageConverter)); + restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); + accessTokenResponseClient.setRestOperations(restTemplate); + return accessTokenResponseClient; + } + + + // additional configuration for non-Spring Boot projects + private static List clients = Arrays.asList("google", "facebook"); + + //@Bean + public ClientRegistrationRepository clientRegistrationRepository() { + List registrations = clients.stream() + .map(c -> getRegistration(c)) + .filter(registration -> registration != null) + .collect(Collectors.toList()); + + return new InMemoryClientRegistrationRepository(registrations); + } + + private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration."; + + @Autowired + private Environment env; + + private ClientRegistration getRegistration(String client) { + String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id"); + + if (clientId == null) { + return null; + } + + String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret"); + if (client.equals("google")) { + return CommonOAuth2Provider.GOOGLE.getBuilder(client) + .clientId(clientId) + .clientSecret(clientSecret) + .build(); + } + if (client.equals("facebook")) { + return CommonOAuth2Provider.FACEBOOK.getBuilder(client) + .clientId(clientId) + .clientSecret(clientSecret) + .build(); + } + return null; + } +} diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2/LoginController.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2/LoginController.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2/MvcConfig.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/MvcConfig.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2/MvcConfig.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2/MvcConfig.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2/SecurityConfig.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SecurityConfig.java similarity index 93% rename from spring-5-security/src/main/java/com/baeldung/oauth2/SecurityConfig.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SecurityConfig.java index b45f325767..e17e339142 100644 --- a/spring-5-security/src/main/java/com/baeldung/oauth2/SecurityConfig.java +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SecurityConfig.java @@ -12,7 +12,7 @@ import org.springframework.core.env.Environment; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.oauth2.client.CommonOAuth2Provider; -import org.springframework.security.oauth2.client.endpoint.NimbusAuthorizationCodeTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient; import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; import org.springframework.security.oauth2.client.registration.ClientRegistration; @@ -54,7 +54,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public OAuth2AccessTokenResponseClient accessTokenResponseClient() { - return new NimbusAuthorizationCodeTokenResponseClient(); + DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient(); + return accessTokenResponseClient; } diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungAuthoritiesExtractor.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungAuthoritiesExtractor.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungAuthoritiesExtractor.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungAuthoritiesExtractor.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungPrincipalExtractor.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungPrincipalExtractor.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungPrincipalExtractor.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/custom/BaeldungPrincipalExtractor.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubAuthoritiesExtractor.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubAuthoritiesExtractor.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubAuthoritiesExtractor.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubAuthoritiesExtractor.java diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubPrincipalExtractor.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubPrincipalExtractor.java similarity index 100% rename from spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubPrincipalExtractor.java rename to spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/extractor/github/GithubPrincipalExtractor.java diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomAuthorizationRequestResolver.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomAuthorizationRequestResolver.java new file mode 100644 index 0000000000..47aacf9c06 --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomAuthorizationRequestResolver.java @@ -0,0 +1,57 @@ +package com.baeldung.oauth2request; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver; +import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver; +import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; + +public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver { + + private OAuth2AuthorizationRequestResolver defaultResolver; + + public CustomAuthorizationRequestResolver(ClientRegistrationRepository repo, String authorizationRequestBaseUri){ + defaultResolver = new DefaultOAuth2AuthorizationRequestResolver(repo, authorizationRequestBaseUri); + } + + @Override + public OAuth2AuthorizationRequest resolve(HttpServletRequest request) { + OAuth2AuthorizationRequest req = defaultResolver.resolve(request); + if(req != null){ + req = customizeAuthorizationRequest(req); + } + return req; + } + + @Override + public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) { + OAuth2AuthorizationRequest req = defaultResolver.resolve(request, clientRegistrationId); + if(req != null){ + req = customizeAuthorizationRequest(req); + } + return req; + } + + private OAuth2AuthorizationRequest customizeAuthorizationRequest(OAuth2AuthorizationRequest req) { + Map extraParams = new HashMap(); + extraParams.putAll(req.getAdditionalParameters()); //VIP note + extraParams.put("test", "extra"); + System.out.println("here ====================="); + return OAuth2AuthorizationRequest.from(req).additionalParameters(extraParams).build(); + } + + private OAuth2AuthorizationRequest customizeAuthorizationRequest1(OAuth2AuthorizationRequest req) { + return OAuth2AuthorizationRequest.from(req).state("xyz").build(); + } + + private OAuth2AuthorizationRequest customizeOktaReq(OAuth2AuthorizationRequest req) { + Map extraParams = new HashMap(); + extraParams.putAll(req.getAdditionalParameters()); + extraParams.put("idp", "https://idprovider.com"); + return OAuth2AuthorizationRequest.from(req).additionalParameters(extraParams).build(); + } +} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomRequestEntityConverter.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomRequestEntityConverter.java new file mode 100644 index 0000000000..5486105c34 --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomRequestEntityConverter.java @@ -0,0 +1,26 @@ +package com.baeldung.oauth2request; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.http.RequestEntity; +import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; +import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequestEntityConverter; +import org.springframework.util.MultiValueMap; + +public class CustomRequestEntityConverter implements Converter> { + + private OAuth2AuthorizationCodeGrantRequestEntityConverter defaultConverter; + + public CustomRequestEntityConverter() { + defaultConverter = new OAuth2AuthorizationCodeGrantRequestEntityConverter(); + } + + @Override + public RequestEntity convert(OAuth2AuthorizationCodeGrantRequest req) { + RequestEntity entity = defaultConverter.convert(req); + MultiValueMap params = (MultiValueMap) entity.getBody(); + params.add("test2", "extra2"); + System.out.println(params.entrySet()); + return new RequestEntity<>(params, entity.getHeaders(), entity.getMethod(), entity.getUrl()); + } + +} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomTokenResponseConverter.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomTokenResponseConverter.java new file mode 100644 index 0000000000..b9775d674a --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/CustomTokenResponseConverter.java @@ -0,0 +1,67 @@ +package com.baeldung.oauth2request; + +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.util.StringUtils; + +public class CustomTokenResponseConverter implements Converter, OAuth2AccessTokenResponse> { + private static final Set TOKEN_RESPONSE_PARAMETER_NAMES = Stream.of( + OAuth2ParameterNames.ACCESS_TOKEN, + OAuth2ParameterNames.TOKEN_TYPE, + OAuth2ParameterNames.EXPIRES_IN, + OAuth2ParameterNames.REFRESH_TOKEN, + OAuth2ParameterNames.SCOPE) .collect(Collectors.toSet()); + + @Override + public OAuth2AccessTokenResponse convert(Map tokenResponseParameters) { + String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN); + + OAuth2AccessToken.TokenType accessTokenType = null; + if (OAuth2AccessToken.TokenType.BEARER.getValue() + .equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) { + accessTokenType = OAuth2AccessToken.TokenType.BEARER; + } + + long expiresIn = 0; + if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) { + try { + expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN)); + } catch (NumberFormatException ex) { + } + } + + Set scopes = Collections.emptySet(); + if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) { + String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE); + scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " ")) + .collect(Collectors.toSet()); + } + + String refreshToken = tokenResponseParameters.get(OAuth2ParameterNames.REFRESH_TOKEN); + + Map additionalParameters = new LinkedHashMap<>(); + tokenResponseParameters.entrySet() + .stream() + .filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey())) + .forEach(e -> additionalParameters.put(e.getKey(), e.getValue())); + + return OAuth2AccessTokenResponse.withToken(accessToken) + .tokenType(accessTokenType) + .expiresIn(expiresIn) + .scopes(scopes) + .refreshToken(refreshToken) + .additionalParameters(additionalParameters) + .build(); + } + +} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/LinkedinTokenResponseConverter.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/LinkedinTokenResponseConverter.java new file mode 100644 index 0000000000..89b3d32de5 --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2request/LinkedinTokenResponseConverter.java @@ -0,0 +1,24 @@ +package com.baeldung.oauth2request; + +import java.util.Map; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; + +public class LinkedinTokenResponseConverter implements Converter, OAuth2AccessTokenResponse> { + + @Override + public OAuth2AccessTokenResponse convert(Map tokenResponseParameters) { + String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN); + long expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN)); + + OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER; + + return OAuth2AccessTokenResponse.withToken(accessToken) + .tokenType(accessTokenType) + .expiresIn(expiresIn) + .build(); + } +} diff --git a/spring-5-security/src/main/resources/application-oauth2-extractors-baeldung.properties b/spring-5-security-oauth/src/main/resources/application-oauth2-extractors-baeldung.properties similarity index 100% rename from spring-5-security/src/main/resources/application-oauth2-extractors-baeldung.properties rename to spring-5-security-oauth/src/main/resources/application-oauth2-extractors-baeldung.properties diff --git a/spring-5-security/src/main/resources/application-oauth2-extractors-github.properties b/spring-5-security-oauth/src/main/resources/application-oauth2-extractors-github.properties similarity index 100% rename from spring-5-security/src/main/resources/application-oauth2-extractors-github.properties rename to spring-5-security-oauth/src/main/resources/application-oauth2-extractors-github.properties diff --git a/spring-5-security/src/main/resources/application-oauth2.properties b/spring-5-security-oauth/src/main/resources/application-oauth2.properties similarity index 100% rename from spring-5-security/src/main/resources/application-oauth2.properties rename to spring-5-security-oauth/src/main/resources/application-oauth2.properties diff --git a/spring-5-security-oauth/src/main/resources/application.properties b/spring-5-security-oauth/src/main/resources/application.properties new file mode 100644 index 0000000000..5912b0f755 --- /dev/null +++ b/spring-5-security-oauth/src/main/resources/application.properties @@ -0,0 +1,5 @@ +server.port=8081 + +logging.level.root=INFO + +logging.level.com.baeldung.dsl.ClientErrorLoggingFilter=DEBUG \ No newline at end of file diff --git a/persistence-modules/spring-hibernate3/src/main/resources/logback.xml b/spring-5-security-oauth/src/main/resources/logback.xml similarity index 100% rename from persistence-modules/spring-hibernate3/src/main/resources/logback.xml rename to spring-5-security-oauth/src/main/resources/logback.xml diff --git a/spring-5-security-oauth/src/main/resources/static/css/main.css b/spring-5-security-oauth/src/main/resources/static/css/main.css new file mode 100644 index 0000000000..febc353af7 --- /dev/null +++ b/spring-5-security-oauth/src/main/resources/static/css/main.css @@ -0,0 +1,8 @@ +p.error { + font-weight: bold; + color: red; +} + +div.logout { + margin-right: 2em;; +} diff --git a/spring-5-security-oauth/src/main/resources/templates/index.html b/spring-5-security-oauth/src/main/resources/templates/index.html new file mode 100644 index 0000000000..4216d74037 --- /dev/null +++ b/spring-5-security-oauth/src/main/resources/templates/index.html @@ -0,0 +1,11 @@ + + + + Home + + + + Home + Welcome! + + \ No newline at end of file diff --git a/spring-5-security/src/main/resources/templates/loginFailure.html b/spring-5-security-oauth/src/main/resources/templates/loginFailure.html similarity index 100% rename from spring-5-security/src/main/resources/templates/loginFailure.html rename to spring-5-security-oauth/src/main/resources/templates/loginFailure.html diff --git a/spring-5-security/src/main/resources/templates/loginSuccess.html b/spring-5-security-oauth/src/main/resources/templates/loginSuccess.html similarity index 100% rename from spring-5-security/src/main/resources/templates/loginSuccess.html rename to spring-5-security-oauth/src/main/resources/templates/loginSuccess.html diff --git a/spring-5-security/src/main/resources/templates/oauth2_extractors.html b/spring-5-security-oauth/src/main/resources/templates/oauth2_extractors.html similarity index 100% rename from spring-5-security/src/main/resources/templates/oauth2_extractors.html rename to spring-5-security-oauth/src/main/resources/templates/oauth2_extractors.html diff --git a/spring-5-security/src/main/resources/templates/oauth_login.html b/spring-5-security-oauth/src/main/resources/templates/oauth_login.html similarity index 100% rename from spring-5-security/src/main/resources/templates/oauth_login.html rename to spring-5-security-oauth/src/main/resources/templates/oauth_login.html diff --git a/spring-5-security/src/main/resources/templates/securedPage.html b/spring-5-security-oauth/src/main/resources/templates/securedPage.html similarity index 100% rename from spring-5-security/src/main/resources/templates/securedPage.html rename to spring-5-security-oauth/src/main/resources/templates/securedPage.html diff --git a/spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java b/spring-5-security-oauth/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java similarity index 100% rename from spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java rename to spring-5-security-oauth/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java diff --git a/spring-5-security/README.md b/spring-5-security/README.md index 55fa7ab042..37dc8b0f28 100644 --- a/spring-5-security/README.md +++ b/spring-5-security/README.md @@ -1,8 +1,7 @@ ## Relevant articles: -- [Spring Security 5 -OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) - [Extra Login Fields with Spring Security](http://www.baeldung.com/spring-security-extra-login-fields) - [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) - [New Password Storage In Spring Security 5](http://www.baeldung.com/spring-security-5-password-storage) - [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) -- [Extracting Principal and Authorities using Spring Security OAuth](https://www.baeldung.com/spring-security-oauth-principal-authorities-extractor) + diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index da62f39fa9..c26e370381 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -33,22 +33,6 @@ org.thymeleaf.extras thymeleaf-extras-springsecurity5 - - - - org.springframework.security.oauth.boot - spring-security-oauth2-autoconfigure - ${oauth-auto.version} - - - org.springframework.security - spring-security-oauth2-client - - - org.springframework.security - spring-security-oauth2-jose - - org.springframework spring-test diff --git a/spring-5-security/src/main/resources/templatesextrafields/index.html b/spring-5-security/src/main/resources/templatesextrafields/index.html index 37833ff0d2..1dd9c12d42 100644 --- a/spring-5-security/src/main/resources/templatesextrafields/index.html +++ b/spring-5-security/src/main/resources/templatesextrafields/index.html @@ -1,5 +1,5 @@ - + Spring Security with Extra Fields diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 293edb5bda..58c14475e0 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -135,7 +135,8 @@ - + org.apache.maven.plugins maven-surefire-plugin @@ -143,14 +144,6 @@ methods true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - diff --git a/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java index ed163f7fa7..82a5fe083b 100644 --- a/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java +++ b/spring-5/src/main/java/com/baeldung/exception/SpringExceptionApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfi import org.springframework.context.annotation.ComponentScan; @SpringBootApplication(exclude = SecurityAutoConfiguration.class) -@ComponentScan(basePackages = { "com.baeldung.execption" }) +@ComponentScan(basePackages = { "com.baeldung.exception" }) public class SpringExceptionApplication { public static void main(String[] args) { SpringApplication.run(SpringExceptionApplication.class, args); diff --git a/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java index 00fce06834..540992b4bc 100644 --- a/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java +++ b/spring-5/src/main/java/com/baeldung/jsonb/Spring5Application.java @@ -6,12 +6,13 @@ import java.util.Collection; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.JsonbHttpMessageConverter; -@SpringBootApplication +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) @ComponentScan(basePackages = { "com.baeldung.jsonb" }) public class Spring5Application { diff --git a/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java index 02332ee7b6..f512b52af4 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java @@ -2,8 +2,9 @@ package com.baeldung.restdocs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -@SpringBootApplication +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) public class SpringRestDocsApplication { public static void main(String[] args) { diff --git a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java index ecc677465e..8b9e66213f 100644 --- a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java @@ -3,12 +3,10 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -@EnableJpaRepositories("com.baeldung.persistence") public class Example1IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java index e1d56c2fc3..6ed53ca4e9 100644 --- a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java @@ -3,12 +3,10 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -@EnableJpaRepositories("com.baeldung.persistence") public class Example2IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index fba01726f4..9c462e0412 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -1,12 +1,11 @@ package com.baeldung.functional; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -14,7 +13,6 @@ import com.baeldung.Spring5Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class) -@EnableJpaRepositories("com.baeldung.persistence") public class BeanRegistrationIntegrationTest { @Autowired diff --git a/spring-all/README.md b/spring-all/README.md index 34e5c3435e..0d78efdcf2 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -33,3 +33,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Cache – Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator) - [Spring @Primary Annotation](http://www.baeldung.com/spring-primary) - [Spring Events](https://www.baeldung.com/spring-events) +- [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 2dc4915bab..77c7e74e08 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -155,6 +155,18 @@ org.apache.logging.log4j log4j-core + + + + net.javacrumbs.shedlock + shedlock-spring + 2.1.0 + + + net.javacrumbs.shedlock + shedlock-provider-jdbc-template + 2.1.0 + diff --git a/spring-amqp-simple/pom.xml b/spring-amqp-simple/pom.xml index 3d9ea55cfa..45cdc066a0 100644 --- a/spring-amqp-simple/pom.xml +++ b/spring-amqp-simple/pom.xml @@ -5,13 +5,13 @@ com.baeldung spring-amqp-simple 1.0.0-SNAPSHOT - Spring AMQP Simple App + spring-amqp-simple - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/SpringAmqpConfig.java b/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/SpringAmqpConfig.java index f6c82b635e..92fa28ed6f 100644 --- a/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/SpringAmqpConfig.java +++ b/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/SpringAmqpConfig.java @@ -35,7 +35,7 @@ public class SpringAmqpConfig { } @Bean - SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, + SimpleMessageListenerContainer springAmqpContainer(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); diff --git a/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/broadcast/BroadcastConfig.java b/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/broadcast/BroadcastConfig.java index 1d02b4dad9..868cfff0ac 100644 --- a/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/broadcast/BroadcastConfig.java +++ b/spring-amqp-simple/src/main/java/com/baeldung/springamqpsimple/broadcast/BroadcastConfig.java @@ -61,7 +61,7 @@ public class BroadcastConfig { } @Bean - public SimpleRabbitListenerContainerFactory container(ConnectionFactory connectionFactory, SimpleRabbitListenerContainerFactoryConfigurer configurer) { + public SimpleRabbitListenerContainerFactory broadcastContainer(ConnectionFactory connectionFactory, SimpleRabbitListenerContainerFactoryConfigurer configurer) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; diff --git a/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-amqp-simple/src/test/java/org/baeldung/SpringContextManualTest.java similarity index 90% rename from spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-amqp-simple/src/test/java/org/baeldung/SpringContextManualTest.java index f134074cf8..03cb34eeb5 100644 --- a/spring-amqp-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-amqp-simple/src/test/java/org/baeldung/SpringContextManualTest.java @@ -9,7 +9,7 @@ import com.baeldung.springamqpsimple.SpringAmqpApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringAmqpApplication.class) -public class SpringContextIntegrationTest { +public class SpringContextManualTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-amqp-simple/src/test/resources/application.yaml b/spring-amqp-simple/src/test/resources/application.yaml new file mode 100644 index 0000000000..aa7a91bac5 --- /dev/null +++ b/spring-amqp-simple/src/test/resources/application.yaml @@ -0,0 +1,5 @@ +spring: + rabbitmq: + username: guest + password: guest + host: localhost \ No newline at end of file diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index 368f3ada14..9e2f97916a 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -6,10 +6,10 @@ spring-aop - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-boot-admin/pom.xml b/spring-boot-admin/pom.xml index 58cea728cc..23852dee57 100644 --- a/spring-boot-admin/pom.xml +++ b/spring-boot-admin/pom.xml @@ -3,6 +3,7 @@ 4.0.0 spring-boot-admin 0.0.1-SNAPSHOT + spring-boot-admin pom diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml index b88587f731..1c3d8796ed 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -5,7 +5,7 @@ spring-boot-autoconfiguration 0.0.1-SNAPSHOT war - spring-boot-auto-configuration + spring-boot-autoconfiguration This is simple boot application demonstrating a custom auto-configuration diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index d6fc1836c7..295e0d74c9 100644 --- a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -47,7 +47,7 @@ public class MySQLAutoconfiguration { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true"); + dataSource.setUrl("jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true&&serverTimezone=UTC"); dataSource.setUsername("mysqluser"); dataSource.setPassword("mysqlpass"); diff --git a/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories b/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories index 5f55544eff..11c775fc6c 100644 --- a/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories +++ b/spring-boot-autoconfiguration/src/main/resources/META-INF/spring.factories @@ -1,3 +1 @@ -org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.baeldung.autoconfiguration.MySQLAutoconfiguration \ No newline at end of file +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.baeldung.autoconfiguration.MySQLAutoconfiguration diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java similarity index 95% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java index 30ba397b46..df4c1fcd14 100644 --- a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationLiveTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) @EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) -public class AutoconfigurationIntegrationTest { +public class AutoconfigurationLiveTest { @Autowired private MyUserRepository userRepository; diff --git a/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java similarity index 88% rename from spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java index 136ea2481f..acd4b10ae9 100644 --- a/spring-boot-autoconfiguration/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/SpringContextLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung.autoconfiguration; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,7 +11,7 @@ import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) @EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) -public class SpringContextIntegrationTest { +public class SpringContextLiveTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 08fdb1bdc9..76b977c129 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -4,3 +4,4 @@ - [Thin JARs with Spring Boot](http://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) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index b5bf4bc7b6..7cafc5aa24 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - org.baeldung + com.baeldung spring-boot-bootstrap jar spring-boot-bootstrap diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java similarity index 78% rename from spring-boot-bootstrap/src/main/java/org/baeldung/Application.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/Application.java index ba1b444e44..567e9b2678 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/Application.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/Application.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -9,9 +9,9 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @ServletComponentScan @SpringBootApplication -@ComponentScan("org.baeldung") -@EnableJpaRepositories("org.baeldung.persistence.repo") -@EntityScan("org.baeldung.persistence.model") +@ComponentScan("com.baeldung") +@EnableJpaRepositories("com.baeldung.persistence.repo") +@EntityScan("com.baeldung.persistence.model") public class Application { public static void main(String[] args) { diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java b/spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java similarity index 93% rename from spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java index b9f9598ca3..7afc036be5 100755 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/cloud/config/CloudDataSourceConfig.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/cloud/config/CloudDataSourceConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.cloud.config; +package com.baeldung.cloud.config; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.Bean; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 95% rename from spring-boot-bootstrap/src/main/java/org/baeldung/config/SecurityConfig.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java index fd37d2ad54..8e403f3976 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/persistence/model/Book.java b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java similarity index 98% rename from spring-boot-bootstrap/src/main/java/org/baeldung/persistence/model/Book.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java index 745a1d0460..6be27d4cf0 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/persistence/model/Book.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.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-boot-bootstrap/src/main/java/org/baeldung/persistence/repo/BookRepository.java b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java similarity index 72% rename from spring-boot-bootstrap/src/main/java/org/baeldung/persistence/repo/BookRepository.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java index 011f3dcb60..cfd0018145 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/persistence/repo/BookRepository.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/repo/BookRepository.java @@ -1,8 +1,9 @@ -package org.baeldung.persistence.repo; +package com.baeldung.persistence.repo; -import org.baeldung.persistence.model.Book; import org.springframework.data.repository.CrudRepository; +import com.baeldung.persistence.model.Book; + import java.util.List; import java.util.Optional; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/BookController.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java similarity index 89% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/BookController.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java index 44129fc7f8..7c86bb833f 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/BookController.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/BookController.java @@ -1,9 +1,5 @@ -package org.baeldung.web; +package com.baeldung.web; -import org.baeldung.persistence.model.Book; -import org.baeldung.persistence.repo.BookRepository; -import org.baeldung.web.exception.BookIdMismatchException; -import org.baeldung.web.exception.BookNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.CrossOrigin; @@ -17,6 +13,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.persistence.model.Book; +import com.baeldung.persistence.repo.BookRepository; +import com.baeldung.web.exception.BookIdMismatchException; +import com.baeldung.web.exception.BookNotFoundException; + import java.util.List; @RestController diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/RestExceptionHandler.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java similarity index 90% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/RestExceptionHandler.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java index cc5b8ee394..dca2e33c52 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/RestExceptionHandler.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/RestExceptionHandler.java @@ -1,7 +1,5 @@ -package org.baeldung.web; +package com.baeldung.web; -import org.baeldung.web.exception.BookIdMismatchException; -import org.baeldung.web.exception.BookNotFoundException; import org.hibernate.exception.ConstraintViolationException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpHeaders; @@ -12,6 +10,9 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import com.baeldung.web.exception.BookIdMismatchException; +import com.baeldung.web.exception.BookNotFoundException; + @ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/SimpleController.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java similarity index 94% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/SimpleController.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java index 809d6c1094..ee0ba75443 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/SimpleController.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/SimpleController.java @@ -1,4 +1,4 @@ -package org.baeldung.web; +package com.baeldung.web; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookIdMismatchException.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java similarity index 92% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookIdMismatchException.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java index 23c55e2d38..bafecd59b6 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookIdMismatchException.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookIdMismatchException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.web.exception; public class BookIdMismatchException extends RuntimeException { diff --git a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookNotFoundException.java b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java similarity index 92% rename from spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookNotFoundException.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java index 3ff416b3f3..42f49e58a3 100644 --- a/spring-boot-bootstrap/src/main/java/org/baeldung/web/exception/BookNotFoundException.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/web/exception/BookNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.web.exception; public class BookNotFoundException extends RuntimeException { diff --git a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapIntegrationTest.java b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java similarity index 89% rename from spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapIntegrationTest.java rename to spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java index 8993617d5c..3af7f2104d 100644 --- a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringBootBootstrapIntegrationTest.java +++ b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringBootBootstrapLiveTest.java @@ -1,28 +1,24 @@ -package org.baeldung; +package com.baeldung; 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 java.util.List; -import org.baeldung.persistence.model.Book; 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 = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) -public class SpringBootBootstrapIntegrationTest { +import com.baeldung.persistence.model.Book; - private static final String API_ROOT = "http://localhost:8081/api/books"; +import io.restassured.RestAssured; +import io.restassured.response.Response; + +public class SpringBootBootstrapLiveTest { + + private static final String API_ROOT = "http://localhost:8080/api/books"; @Test public void whenGetAllBooks_thenOK() { diff --git a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 93% rename from spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 9ae417a546..08c6692689 100644 --- a/spring-boot-bootstrap/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextIntegrationTest.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-camel/pom.xml b/spring-boot-camel/pom.xml index 19a0bec809..8bab0ed5c8 100644 --- a/spring-boot-camel/pom.xml +++ b/spring-boot-camel/pom.xml @@ -5,7 +5,8 @@ com.example spring-boot-camel 0.0.1-SNAPSHOT - + spring-boot-camel + com.baeldung parent-modules diff --git a/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index 71fb330663..d423300b85 100644 --- a/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -10,7 +10,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; @@ -18,8 +17,7 @@ import org.springframework.test.web.client.MockRestServiceServer; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@RestClientTest(DetailsServiceClient.class) +@RestClientTest({ DetailsServiceClient.class, Application.class }) public class DetailsServiceClientIntegrationTest { @Autowired @@ -34,7 +32,8 @@ public class DetailsServiceClientIntegrationTest { @Before public void setUp() throws Exception { String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); + this.server.expect(requestTo("/john/details")) + .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test diff --git a/spring-boot-crud/pom.xml b/spring-boot-crud/pom.xml index f803a7e70b..749bf9cb5a 100644 --- a/spring-boot-crud/pom.xml +++ b/spring-boot-crud/pom.xml @@ -3,10 +3,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - com.baeldung.spring-boot-crud spring-boot-crud 0.1.0 + spring-boot-crud org.springframework.boot 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 index 436cccb964..0b686e90e9 100644 --- a/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java +++ b/spring-boot-crud/src/main/java/com/baeldung/crud/Application.java @@ -14,11 +14,10 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableJpaRepositories(basePackages="com.baeldung.crud.repositories") @EnableTransactionManagement @EntityScan(basePackages="com.baeldung.crud.entities") - -@SpringBootApplication 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 index 1b7185c2fd..9a6cb477aa 100644 --- 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 @@ -1,8 +1,7 @@ package com.baeldung.crud.controllers; -import com.baeldung.crud.UserRepository; -import com.baeldung.crud.entities.User; import javax.validation.Valid; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -11,6 +10,9 @@ 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 { diff --git a/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java b/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java index 7773a962fb..2de0828ae5 100644 --- a/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java +++ b/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java @@ -1,16 +1,18 @@ package com.baeldung.crud; -import com.baeldung.crud.UserController; -import com.baeldung.crud.entities.User; -import com.baeldung.crud.UserRepository; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.BeforeClass; -import org.junit.Test; 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; 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 index a3c6a922d8..565f6727c3 100644 --- a/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java +++ b/spring-boot-crud/src/test/java/com/baeldung/crud/UserUnitTest.java @@ -1,9 +1,11 @@ package com.baeldung.crud; -import com.baeldung.crud.User; import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; +import com.baeldung.crud.entities.User; + public class UserUnitTest { @Test diff --git a/spring-boot-ctx-fluent/pom.xml b/spring-boot-ctx-fluent/pom.xml index f9b691aea7..b238374612 100644 --- a/spring-boot-ctx-fluent/pom.xml +++ b/spring-boot-ctx-fluent/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung spring-boot-ctx-fluent 0.0.1-SNAPSHOT + spring-boot-ctx-fluent jar diff --git a/spring-boot-custom-starter/greeter-library/pom.xml b/spring-boot-custom-starter/greeter-library/pom.xml index 3717ba005c..7e0c5c4d22 100644 --- a/spring-boot-custom-starter/greeter-library/pom.xml +++ b/spring-boot-custom-starter/greeter-library/pom.xml @@ -1,10 +1,11 @@ 4.0.0 - com.baeldung greeter-library 0.0.1-SNAPSHOT + greeter-library + spring-boot-custom-starter com.baeldung diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 5862bdd6c8..1e4ee698c6 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung greeter-spring-boot-autoconfigure 0.0.1-SNAPSHOT + greeter-spring-boot-autoconfigure spring-boot-custom-starter diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 88c5d1caf5..91cc41d669 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung greeter-spring-boot-sample-app 0.0.1-SNAPSHOT + greeter-spring-boot-sample-app spring-boot-custom-starter diff --git a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml index e71882db29..560d6fa79b 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung greeter-spring-boot-starter 0.0.1-SNAPSHOT + greeter-spring-boot-starter spring-boot-custom-starter diff --git a/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-custom-starter/greeter/pom.xml index 3cfd6da09e..95fcaa66c8 100644 --- a/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-custom-starter/greeter/pom.xml @@ -1,10 +1,11 @@ 4.0.0 - com.baeldung greeter 0.0.1-SNAPSHOT + greeter + parent-boot-1 com.baeldung diff --git a/spring-boot-custom-starter/pom.xml b/spring-boot-custom-starter/pom.xml index 97b33ce2b8..9c03cfdd0e 100644 --- a/spring-boot-custom-starter/pom.xml +++ b/spring-boot-custom-starter/pom.xml @@ -4,6 +4,7 @@ com.baeldung spring-boot-custom-starter 0.0.1-SNAPSHOT + spring-boot-custom-starter pom diff --git a/spring-boot-disable-console-logging/disabling-console-jul/.gitignore b/spring-boot-disable-console-logging/disabling-console-jul/.gitignore new file mode 100644 index 0000000000..ff56635e49 --- /dev/null +++ b/spring-boot-disable-console-logging/disabling-console-jul/.gitignore @@ -0,0 +1 @@ +baeldung.log diff --git a/spring-boot-disable-console-logging/disabling-console-jul/pom.xml b/spring-boot-disable-console-logging/disabling-console-jul/pom.xml index ceac0616e9..9ccbd56231 100644 --- a/spring-boot-disable-console-logging/disabling-console-jul/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-jul/pom.xml @@ -2,13 +2,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 disabling-console-jul - + disabling-console-jul org.springframework.boot spring-boot-starter-parent - 2.0.5.RELEASE + 2.1.1.RELEASE diff --git a/spring-boot-disable-console-logging/disabling-console-log4j2/.gitignore b/spring-boot-disable-console-logging/disabling-console-log4j2/.gitignore new file mode 100644 index 0000000000..d3ae44ddfc --- /dev/null +++ b/spring-boot-disable-console-logging/disabling-console-log4j2/.gitignore @@ -0,0 +1 @@ +all.log diff --git a/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml b/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml index d6e9a8b5e5..0b360bb366 100644 --- a/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-log4j2/pom.xml @@ -2,13 +2,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 disabling-console-log4j2 - + disabling-console-log4j2 org.springframework.boot spring-boot-starter-parent - 2.0.5.RELEASE + 2.1.1.RELEASE diff --git a/spring-boot-disable-console-logging/disabling-console-logback/.gitignore b/spring-boot-disable-console-logging/disabling-console-logback/.gitignore new file mode 100644 index 0000000000..4e6aa917ed --- /dev/null +++ b/spring-boot-disable-console-logging/disabling-console-logback/.gitignore @@ -0,0 +1 @@ +disabled-console.log diff --git a/spring-boot-disable-console-logging/disabling-console-logback/pom.xml b/spring-boot-disable-console-logging/disabling-console-logback/pom.xml index f18066ea03..4b64885c66 100644 --- a/spring-boot-disable-console-logging/disabling-console-logback/pom.xml +++ b/spring-boot-disable-console-logging/disabling-console-logback/pom.xml @@ -1,17 +1,22 @@ - - 4.0.0 - - com.baeldung - spring-boot-disable-console-logging - 0.0.1-SNAPSHOT - - disabling-console-logback - - - - org.springframework.boot - spring-boot-starter-web - - - + + 4.0.0 + disabling-console-logback + disabling-console-logback + + + spring-boot-disable-console-logging + com.baeldung + 0.0.1-SNAPSHOT + ../ + + + + + org.springframework.boot + spring-boot-starter-web + + + \ No newline at end of file diff --git a/spring-boot-disable-console-logging/pom.xml b/spring-boot-disable-console-logging/pom.xml index ec84372f99..63ed129347 100644 --- a/spring-boot-disable-console-logging/pom.xml +++ b/spring-boot-disable-console-logging/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-disable-console-logging + spring-boot-disable-console-logging pom Projects for Disabling Spring Boot Console Logging tutorials diff --git a/spring-boot-libraries/.gitignore b/spring-boot-libraries/.gitignore new file mode 100644 index 0000000000..da7c2c5c0a --- /dev/null +++ b/spring-boot-libraries/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project + diff --git a/spring-boot-libraries/.mvn/wrapper/maven-wrapper.jar b/spring-boot-libraries/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000..5fd4d5023f Binary files /dev/null and b/spring-boot-libraries/.mvn/wrapper/maven-wrapper.jar differ diff --git a/spring-boot-libraries/README.MD b/spring-boot-libraries/README.MD new file mode 100644 index 0000000000..cc32ce8355 --- /dev/null +++ b/spring-boot-libraries/README.MD @@ -0,0 +1,6 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Guide to ShedLock with Spring](https://www.baeldung.com/shedlock-spring) diff --git a/mvn-wrapper/mvnw b/spring-boot-libraries/mvnw old mode 100755 new mode 100644 similarity index 100% rename from mvn-wrapper/mvnw rename to spring-boot-libraries/mvnw diff --git a/mvn-wrapper/mvnw.cmd b/spring-boot-libraries/mvnw.cmd old mode 100755 new mode 100644 similarity index 97% rename from mvn-wrapper/mvnw.cmd rename to spring-boot-libraries/mvnw.cmd index 4f0b068a03..6a6eec39ba --- a/mvn-wrapper/mvnw.cmd +++ b/spring-boot-libraries/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-libraries/pom.xml b/spring-boot-libraries/pom.xml new file mode 100644 index 0000000000..c28128c5f0 --- /dev/null +++ b/spring-boot-libraries/pom.xml @@ -0,0 +1,144 @@ + + 4.0.0 + spring-boot-libraries + war + spring-boot-libraries + This is simple boot application for Spring boot actuator test + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-test + test + + + + + net.javacrumbs.shedlock + shedlock-spring + 2.1.0 + + + net.javacrumbs.shedlock + shedlock-provider-jdbc-template + 2.1.0 + + + + + + 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 + 2.3.2 + + + diff --git a/spring-boot-libraries/src/main/java/com/baeldung/Application.java b/spring-boot-libraries/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..c1b6558b26 --- /dev/null +++ b/spring-boot-libraries/src/main/java/com/baeldung/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java new file mode 100644 index 0000000000..74ea39683d --- /dev/null +++ b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -0,0 +1,12 @@ +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 new file mode 100644 index 0000000000..b1b1ad921f --- /dev/null +++ b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java @@ -0,0 +1,15 @@ +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"); + } +} \ No newline at end of file diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index 38dc5fb341..ad678a14cf 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - spring-boot-logging-log4j2 jar + spring-boot-logging-log4j2 Demo project for Spring Boot Logging with Log4J2 diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java index ab90d8cef2..9ace79c085 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java @@ -3,11 +3,11 @@ package com.baeldung.annotations; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -// @SpringBootApplication + @SpringBootApplication public class VehicleFactoryApplication { -// public static void main(String[] args) { -// SpringApplication.run(VehicleFactoryApplication.class, args); -// } + public static void main(String[] args) { + SpringApplication.run(VehicleFactoryApplication.class, args); + } } diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 57779c3f8e..9717a352d3 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -86,6 +86,12 @@ ${jquery.version} + + org.springframework.cloud + spring-cloud-context + ${springcloud.version} + + @@ -153,6 +159,7 @@ 2.2 18.0 3.1.7 + 2.0.2.RELEASE diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java b/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java new file mode 100644 index 0000000000..a6605a0baa --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java @@ -0,0 +1,30 @@ +package com.baeldung.restart; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.ConfigurableApplicationContext; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + private static ConfigurableApplicationContext context; + + public static void main(String[] args) { + context = SpringApplication.run(Application.class, args); + } + + public static void restart() { + ApplicationArguments args = context.getBean(ApplicationArguments.class); + + Thread thread = new Thread(() -> { + context.close(); + context = SpringApplication.run(Application.class, args.getSourceArgs()); + }); + + thread.setDaemon(false); + thread.start(); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java new file mode 100644 index 0000000000..68a8dc7073 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java @@ -0,0 +1,23 @@ +package com.baeldung.restart; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RestartController { + + @Autowired + private RestartService restartService; + + @PostMapping("/restart") + public void restart() { + Application.restart(); + } + + @PostMapping("/restartApp") + public void restartUsingActuator() { + restartService.restartApp(); + } + +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java new file mode 100644 index 0000000000..9883ec653b --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java @@ -0,0 +1,17 @@ +package com.baeldung.restart; + +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.context.restart.RestartEndpoint; + +@Service +public class RestartService { + + @Autowired + private RestartEndpoint restartEndpoint; + + public void restartApp() { + restartEndpoint.restart(); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/resources/application.properties b/spring-boot-ops/src/main/resources/application.properties index a86bd3052e..27b7915cff 100644 --- a/spring-boot-ops/src/main/resources/application.properties +++ b/spring-boot-ops/src/main/resources/application.properties @@ -1,3 +1,7 @@ management.endpoints.web.exposure.include=* management.metrics.enable.root=true -management.metrics.enable.jvm=true \ No newline at end of file +management.metrics.enable.jvm=true +management.endpoint.restart.enabled=true +spring.datasource.jmx-enabled=false +spring.main.allow-bean-definition-overriding=true +management.endpoint.shutdown.enabled=true \ No newline at end of file diff --git a/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java new file mode 100644 index 0000000000..14e80c3ac7 --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.restart; + +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; + +import java.time.Duration; + +public class RestartApplicationIntegrationTest { + + private TestRestTemplate restTemplate = new TestRestTemplate(); + + @Test + public void givenBootApp_whenRestart_thenOk() throws Exception { + Application.main(new String[0]); + + ResponseEntity response = restTemplate.exchange("http://localhost:8080/restart", + HttpMethod.POST, null, Object.class); + + assertEquals(200, response.getStatusCode().value()); + } + + @Test + public void givenBootApp_whenRestartUsingActuator_thenOk() throws Exception { + Application.main(new String[] { "--server.port=8090" }); + + ResponseEntity response = restTemplate.exchange("http://localhost:8090/restartApp", + HttpMethod.POST, null, Object.class); + + assertEquals(200, response.getStatusCode().value()); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/test/resources/application.properties b/spring-boot-ops/src/test/resources/application.properties index 2095a82a14..cf0f0ab74c 100644 --- a/spring-boot-ops/src/test/resources/application.properties +++ b/spring-boot-ops/src/test/resources/application.properties @@ -4,4 +4,9 @@ spring.mail.properties.mail.smtp.auth=false management.endpoints.web.exposure.include=* management.endpoint.shutdown.enabled=true -endpoints.shutdown.enabled=true \ No newline at end of file +endpoints.shutdown.enabled=true + +management.endpoint.restart.enabled=true + +spring.main.allow-bean-definition-overriding=true +spring.jmx.unique-names=true \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index ab22c5ad30..9988924408 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -1,11 +1,10 @@ 4.0.0 - property-exp-custom - com.baeldung property-exp-custom-config 0.0.1-SNAPSHOT + property-exp-custom-config jar diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index 4ede36e61a..7892288f45 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -1,11 +1,10 @@ 4.0.0 - property-exp-default - com.baeldung property-exp-default-config 0.0.1-SNAPSHOT + property-exp-default-config jar diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index d5c7976ba2..b87189757a 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -66,4 +66,8 @@ + + com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication + + diff --git a/spring-boot-testing/.gitignore b/spring-boot-testing/.gitignore new file mode 100644 index 0000000000..da7c2c5c0a --- /dev/null +++ b/spring-boot-testing/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project + diff --git a/mvn-wrapper/.mvn/wrapper/maven-wrapper.jar b/spring-boot-testing/.mvn/wrapper/maven-wrapper.jar old mode 100755 new mode 100644 similarity index 72% rename from mvn-wrapper/.mvn/wrapper/maven-wrapper.jar rename to spring-boot-testing/.mvn/wrapper/maven-wrapper.jar index f775b1c04c..9cc84ea9b4 Binary files a/mvn-wrapper/.mvn/wrapper/maven-wrapper.jar and b/spring-boot-testing/.mvn/wrapper/maven-wrapper.jar differ diff --git a/mvn-wrapper/.mvn/wrapper/maven-wrapper.properties b/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties old mode 100755 new mode 100644 similarity index 100% rename from mvn-wrapper/.mvn/wrapper/maven-wrapper.properties rename to spring-boot-testing/.mvn/wrapper/maven-wrapper.properties diff --git a/spring-boot-testing/README.MD b/spring-boot-testing/README.MD new file mode 100644 index 0000000000..a609b5bf09 --- /dev/null +++ b/spring-boot-testing/README.MD @@ -0,0 +1,6 @@ +### 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) diff --git a/spring-boot-testing/mvnw b/spring-boot-testing/mvnw new file mode 100644 index 0000000000..e96ccd5fbb --- /dev/null +++ b/spring-boot-testing/mvnw @@ -0,0 +1,227 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-testing/mvnw.cmd b/spring-boot-testing/mvnw.cmd new file mode 100644 index 0000000000..6a6eec39ba --- /dev/null +++ b/spring-boot-testing/mvnw.cmd @@ -0,0 +1,145 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/spring-boot-testing/pom.xml b/spring-boot-testing/pom.xml new file mode 100644 index 0000000000..2a498e54c5 --- /dev/null +++ b/spring-boot-testing/pom.xml @@ -0,0 +1,150 @@ + + 4.0.0 + spring-boot-testing + war + spring-boot-testing + This is simple boot application for demonstrating testing features. + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.spockframework + spock-core + ${spock.version} + test + + + + org.spockframework + spock-spring + ${spock.version} + test + + + + + 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 + + + + + org.codehaus.gmavenplus + gmavenplus-plugin + 1.6 + + + + compileTests + + + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + org.baeldung.boot.Application + 2.2.4 + 1.2-groovy-2.4 + + + diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java b/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..c1b6558b26 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java b/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java new file mode 100644 index 0000000000..5b65599e00 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java @@ -0,0 +1,36 @@ +package org.baeldung.boot.controller.rest; + +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.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 java.util.Optional; + +@RestController +@RequestMapping("/hello") +public class WebController { + + private String name; + + @GetMapping + public String salutation() { + return "Hello " + Optional.ofNullable(name).orElse("world") + '!'; + } + + @PutMapping + @ResponseStatus(HttpStatus.NO_CONTENT) + public void setName(@RequestBody final String name) { + this.name = name; + } + + @DeleteMapping + @ResponseStatus(HttpStatus.NO_CONTENT) + public void resetToDefault() { + this.name = null; + } +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/groovy/org/baeldung/boot/LoadContextTest.groovy b/spring-boot-testing/src/test/groovy/org/baeldung/boot/LoadContextTest.groovy new file mode 100644 index 0000000000..2d4a7ca2cf --- /dev/null +++ b/spring-boot-testing/src/test/groovy/org/baeldung/boot/LoadContextTest.groovy @@ -0,0 +1,23 @@ +package org.baeldung.boot + +import org.baeldung.boot.controller.rest.WebController +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import spock.lang.Narrative +import spock.lang.Specification +import spock.lang.Title + +@Title("Application Specification") +@Narrative("Specification which beans are expected") +@SpringBootTest +class LoadContextTest extends Specification { + + @Autowired(required = false) + private WebController webController + + + def "when context is loaded then all expected beans are created"() { + expect: "the WebController is created" + webController + } +} diff --git a/spring-boot-testing/src/test/groovy/org/baeldung/boot/WebControllerTest.groovy b/spring-boot-testing/src/test/groovy/org/baeldung/boot/WebControllerTest.groovy new file mode 100644 index 0000000000..fe1b34ab8c --- /dev/null +++ b/spring-boot-testing/src/test/groovy/org/baeldung/boot/WebControllerTest.groovy @@ -0,0 +1,43 @@ +package org.baeldung.boot + +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.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders +import org.springframework.test.web.servlet.result.MockMvcResultMatchers +import spock.lang.Narrative +import spock.lang.Specification +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 +@WebMvcTest +class WebControllerTest extends Specification { + + @Autowired + private MockMvc mvc + + def "when get is performed then the response has status 200 and content is 'Hello world!'"() { + expect: "Status is 200 and the response is 'Hello world!'" + mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!" + } + + def "when set and delete are performed then the response has status 204 and content changes as expected"() { + given: "a new name" + def NAME = "Emmy" + + when: "the name is set" + mvc.perform(MockMvcRequestBuilders.put("/hello").content(NAME)).andExpect(MockMvcResultMatchers.status().isNoContent()) + + then: "the salutation uses the new name" + mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello $NAME!" + + when: "the name is deleted" + mvc.perform(MockMvcRequestBuilders.delete("/hello")).andExpect(MockMvcResultMatchers.status().isNoContent()) + + then: "the salutation uses the default name" + mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!" + } +} diff --git a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java similarity index 95% rename from spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java rename to spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java index 567b239ed2..7d8accf813 100644 --- a/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationUnitTest.java +++ b/spring-boot-vue/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -public class SpringBootMvcApplicationUnitTest { +public class SpringBootMvcApplicationIntegrationTest { @Autowired private MockMvc mockMvc; diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 016d2841d7..2a6a935cc1 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -25,7 +25,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) - [A Quick Intro to the SpringBootServletInitializer](http://www.baeldung.com/spring-boot-servlet-initializer) - [How to Define a Spring Boot Filter?](http://www.baeldung.com/spring-boot-add-filter) -- [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port) - [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes) - [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 87c782b044..e6866b5a8f 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -162,6 +162,12 @@ javax.validation validation-api + + + org.modelmapper + modelmapper + ${modelmapper.version} + @@ -259,6 +265,7 @@ 5.2.4 18.0 2.2.4 + 2.3.2 diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java b/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java new file mode 100644 index 0000000000..7684c43648 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java @@ -0,0 +1,20 @@ +package com.baeldung.modelmapper; + +import org.modelmapper.ModelMapper; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class PostApplication { + + public static void main(String[] args) { + SpringApplication.run(PostApplication.class, args); + } + + @Bean + public ModelMapper modelMapper() { + return new ModelMapper(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java b/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java new file mode 100644 index 0000000000..c0cbca5220 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java @@ -0,0 +1,91 @@ +package com.baeldung.modelmapper.controller; + +import java.text.ParseException; +import java.util.List; +import java.util.stream.Collectors; + +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +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 com.baeldung.modelmapper.dto.PostDto; +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.service.IPostService; +import com.baeldung.modelmapper.service.IUserService; + +@Controller +public class PostRestController { + + @Autowired + private IPostService postService; + + @Autowired + private IUserService userService; + + @Autowired + private ModelMapper modelMapper; + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List getPosts( + @PathVariable("page") int page, + @PathVariable("size") int size, + @PathVariable("sortDir") String sortDir, + @PathVariable("sort") String sort) { + + List posts = postService.getPostsList(page, size, sortDir, sort); + return posts.stream() + .map(post -> convertToDto(post)) + .collect(Collectors.toList()); + } + + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public PostDto createPost(@RequestBody PostDto postDto) throws ParseException { + Post post = convertToEntity(postDto); + Post postCreated = postService.createPost(post); + return convertToDto(postCreated); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public PostDto getPost(@PathVariable("id") Long id) { + return convertToDto(postService.getPostById(id)); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.OK) + public void updatePost(@RequestBody PostDto postDto) throws ParseException { + Post post = convertToEntity(postDto); + postService.updatePost(post); + } + + + private PostDto convertToDto(Post post) { + PostDto postDto = modelMapper.map(post, PostDto.class); + postDto.setSubmissionDate(post.getSubmissionDate(), + userService.getCurrentUser().getPreference().getTimezone()); + return postDto; + } + + private Post convertToEntity(PostDto postDto) throws ParseException { + Post post = modelMapper.map(postDto, Post.class); + post.setSubmissionDate(postDto.getSubmissionDateConverted( + userService.getCurrentUser().getPreference().getTimezone())); + + if (postDto.getId() != null) { + Post oldPost = postService.getPostById(postDto.getId()); + post.setRedditID(oldPost.getRedditID()); + post.setSent(oldPost.isSent()); + } + return post; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java new file mode 100644 index 0000000000..6fe2b23888 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java @@ -0,0 +1,71 @@ +package com.baeldung.modelmapper.dto; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +public class PostDto { + + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + + private Long id; + + private String title; + + private String url; + + private String date; + + private UserDto user; + + public Date getSubmissionDateConverted(String timezone) throws ParseException { + dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); + return dateFormat.parse(this.date); + } + + public void setSubmissionDate(Date date, String timezone) { + dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); + this.date = dateFormat.format(date); + } + + 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 UserDto getUser() { + return user; + } + + public void setUser(UserDto user) { + this.user = user; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java new file mode 100644 index 0000000000..23110ecbaa --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java @@ -0,0 +1,14 @@ +package com.baeldung.modelmapper.dto; + +public class UserDto { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java new file mode 100644 index 0000000000..be65ce34a2 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java @@ -0,0 +1,98 @@ +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/src/main/java/com/baeldung/modelmapper/model/Preference.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java new file mode 100644 index 0000000000..0ab5b1eddf --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java @@ -0,0 +1,32 @@ +package com.baeldung.modelmapper.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Preference { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String timezone; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java new file mode 100644 index 0000000000..a458b26f4a --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java @@ -0,0 +1,44 @@ +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/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java b/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java new file mode 100644 index 0000000000..fc3f5733c3 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java @@ -0,0 +1,21 @@ +package com.baeldung.modelmapper.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +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; + +public interface PostRepository extends JpaRepository, PagingAndSortingRepository { + + @Query("select u from Post u where u.userName=:userName") + Page findByUser(@Param("userName") String userName, Pageable pageReq); + + default Page findByUser(User user, Pageable pageReq) { + return findByUser(user.getName(), pageReq); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java new file mode 100644 index 0000000000..0182a0da41 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java @@ -0,0 +1,17 @@ +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/src/main/java/com/baeldung/modelmapper/service/IUserService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java new file mode 100644 index 0000000000..79934114c1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java @@ -0,0 +1,9 @@ +package com.baeldung.modelmapper.service; + +import com.baeldung.modelmapper.model.User; + +public interface IUserService { + + User getCurrentUser(); + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java new file mode 100644 index 0000000000..5980c30837 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java @@ -0,0 +1,47 @@ +package com.baeldung.modelmapper.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.repository.PostRepository; + +@Service +public class PostService implements IPostService { + + @Autowired + private PostRepository postRepository; + + @Autowired + private IUserService userService; + + @Override + public List getPostsList(int page, int size, String sortDir, String sort) { + + PageRequest pageReq + = PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort); + + Page posts = postRepository.findByUser(userService.getCurrentUser(), pageReq); + return posts.getContent(); + } + + @Override + public void updatePost(Post post) { + postRepository.save(post); + } + + @Override + public Post createPost(Post post) { + return postRepository.save(post); + } + + @Override + public Post getPostById(Long id) { + return postRepository.getOne(id); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java new file mode 100644 index 0000000000..e445f836a4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java @@ -0,0 +1,25 @@ +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/src/main/java/com/baeldung/properties/ConfigProperties.java b/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java index 863510738b..35b0239287 100644 --- a/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java +++ b/spring-boot/src/main/java/com/baeldung/properties/ConfigProperties.java @@ -5,10 +5,10 @@ import java.util.Map; import javax.validation.constraints.Max; import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Length; -import org.hibernate.validator.constraints.NotBlank; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; diff --git a/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java b/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java index 2c815fe998..2d3e56100c 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigProperties.java @@ -5,10 +5,10 @@ import java.util.Map; import javax.validation.constraints.Max; import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Length; -import org.hibernate.validator.constraints.NotBlank; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; diff --git a/spring-boot/src/main/resources/templates/customer.html b/spring-boot/src/main/resources/templates/customer.html new file mode 100644 index 0000000000..c8f5a25d5e --- /dev/null +++ b/spring-boot/src/main/resources/templates/customer.html @@ -0,0 +1,16 @@ + + + +Customer Page + + + +
+
+Contact Info:
+ +
+

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

+ Hello, --name--. +

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

+

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

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 new file mode 100644 index 0000000000..5ddf458229 --- /dev/null +++ b/spring-boot/src/main/resources/templates/error-500.html @@ -0,0 +1,16 @@ + + + + + + + +
+
+

Sorry, something went wrong!

+ +

We're fixing it.

+

Go Home

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

Something went wrong!

+ +

Our Engineers are on it.

+

Go Home

+
+ + diff --git a/spring-boot/src/main/resources/templates/error/404.html b/spring-boot/src/main/resources/templates/error/404.html new file mode 100644 index 0000000000..df83ce219b --- /dev/null +++ b/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/src/main/resources/templates/external.html new file mode 100644 index 0000000000..2f9cc76961 --- /dev/null +++ b/spring-boot/src/main/resources/templates/external.html @@ -0,0 +1,31 @@ + + + + + +
+
+

Customer Portal

+
+
+

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

+ +

Existing Customers

+
+ Enter the intranet: customers +
+
+ +
+ + + + diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot/src/main/resources/templates/index.html new file mode 100644 index 0000000000..c1314558f6 --- /dev/null +++ b/spring-boot/src/main/resources/templates/index.html @@ -0,0 +1,19 @@ + + + WebJars Demo + + + +

Welcome Home

+

+
+ × + Success! It is working as we expected. +
+
+ + + + + + diff --git a/spring-boot/src/main/resources/templates/international.html b/spring-boot/src/main/resources/templates/international.html new file mode 100644 index 0000000000..e0cfb5143b --- /dev/null +++ b/spring-boot/src/main/resources/templates/international.html @@ -0,0 +1,20 @@ + + + + +Home + + + + +

+ +

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

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

+

Set Parameter:

+

+ + +

+
+Another Page + + \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index 44461c0cf6..2785054153 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -1,20 +1,19 @@ package com.baeldung.intro; +import static org.hamcrest.Matchers.equalTo; +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.http.MediaType; -import org.springframework.test.context.TestPropertySource; 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.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc diff --git a/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java b/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java new file mode 100644 index 0000000000..34ec4db783 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.modelmapper; + +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; + +public class PostDtoUnitTest { + + private ModelMapper modelMapper = new ModelMapper(); + + @Test + public void whenConvertPostEntityToPostDto_thenCorrect() { + Post post = new Post(); + post.setId(Long.valueOf(1)); + post.setTitle(randomAlphabetic(6)); + post.setUrl("www.test.com"); + + PostDto postDto = modelMapper.map(post, PostDto.class); + assertEquals(post.getId(), postDto.getId()); + assertEquals(post.getTitle(), postDto.getTitle()); + assertEquals(post.getUrl(), postDto.getUrl()); + } + + @Test + public void whenConvertPostDtoToPostEntity_thenCorrect() { + PostDto postDto = new PostDto(); + postDto.setId(Long.valueOf(1)); + postDto.setTitle(randomAlphabetic(6)); + postDto.setUrl("www.test.com"); + + Post post = modelMapper.map(postDto, Post.class); + assertEquals(postDto.getId(), post.getId()); + assertEquals(postDto.getTitle(), post.getTitle()); + assertEquals(postDto.getUrl(), post.getUrl()); + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java index 5431217c3e..39127f62e9 100644 --- a/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/mongodb/MongoDbSpringIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.mongodb; import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.boot.Application; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java index fba816c681..0541da3199 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java @@ -4,12 +4,11 @@ import org.baeldung.demo.DemoApplication; 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.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = DemoApplication.class) -@WebAppConfiguration +@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class DemoApplicationIntegrationTest { @Test diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java index 640a8b322a..2d70583a54 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java @@ -45,10 +45,10 @@ public class EmployeeControllerIntegrationTest { @Test public void whenPostEmployee_thenCreateEmployee() throws Exception { Employee alex = new Employee("alex"); - given(service.save(Mockito.anyObject())).willReturn(alex); + given(service.save(Mockito.any())).willReturn(alex); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex"))); - verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject()); + verify(service, VerificationModeFactory.times(1)).save(Mockito.any()); reset(service); } diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index d76dbfc803..a4b35889d6 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -22,13 +22,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = DemoApplication.class) -@AutoConfigureMockMvc +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) +@AutoConfigureMockMvc // @TestPropertySource(locations = "classpath:application-integrationtest.properties") @AutoConfigureTestDatabase public class EmployeeRestControllerIntegrationTest { diff --git a/spring-cloud-bus/pom.xml b/spring-cloud-bus/pom.xml index d493c4e984..784e4cbae6 100644 --- a/spring-cloud-bus/pom.xml +++ b/spring-cloud-bus/pom.xml @@ -7,6 +7,7 @@ spring-cloud-bus 1.0.0-SNAPSHOT pom + spring-cloud-bus parent-boot-1 diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index 0133d65978..a02d2984c1 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/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 - org.baeldung.spring.cloud data-flow-server 0.0.1-SNAPSHOT jar diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index e4ec145277..3b155736c3 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/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 - org.baeldung.spring.cloud data-flow-shell 0.0.1-SNAPSHOT jar diff --git a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml index 468d8e17d0..1f16a02a98 100644 --- a/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml +++ b/spring-cloud-data-flow/etl/customer-mongodb-sink/pom.xml @@ -1,10 +1,8 @@ - 4.0.0 - com.customer customer-mongodb-sink jar @@ -17,13 +15,6 @@ 0.0.1-SNAPSHOT ../../../parent-boot-2 - - - UTF-8 - UTF-8 - 1.8 - Finchley.SR1 - @@ -71,5 +62,22 @@
+ + + spring-milestones + Spring Milestones + http://repo.spring.io/milestone + + false + + + + + + UTF-8 + UTF-8 + 1.8 + Greenwich.M3 + diff --git a/spring-cloud-data-flow/etl/customer-transform/pom.xml b/spring-cloud-data-flow/etl/customer-transform/pom.xml index bc4b648907..ed281b420a 100644 --- a/spring-cloud-data-flow/etl/customer-transform/pom.xml +++ b/spring-cloud-data-flow/etl/customer-transform/pom.xml @@ -1,12 +1,9 @@ - 4.0.0 - com.customer customer-transform - 0.0.1-SNAPSHOT jar customer-transform @@ -19,13 +16,6 @@ ../../../parent-boot-2 - - UTF-8 - UTF-8 - 1.8 - Finchley.SR1 - - org.springframework.cloud @@ -64,5 +54,22 @@ + + + spring-milestones + Spring Milestones + http://repo.spring.io/milestone + + false + + + + + + UTF-8 + UTF-8 + 1.8 + Greenwich.M3 + diff --git a/spring-cloud-data-flow/etl/pom.xml b/spring-cloud-data-flow/etl/pom.xml index 2b904f6e0d..7d5040e8ad 100644 --- a/spring-cloud-data-flow/etl/pom.xml +++ b/spring-cloud-data-flow/etl/pom.xml @@ -1,13 +1,13 @@ 4.0.0 - org.baeldung.spring.cloud - etl-spring-cloud-data-flow + etl + etl 0.0.1-SNAPSHOT pom - + - org.baeldung.spring.cloud + com.baeldung spring-cloud-data-flow 0.0.1-SNAPSHOT diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index 33a0a4df45..69de679c2a 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/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 - org.baeldung.spring.cloud log-sink 0.0.1-SNAPSHOT jar diff --git a/spring-cloud-data-flow/pom.xml b/spring-cloud-data-flow/pom.xml index 5a007f3c7d..b5ef5d2c2a 100644 --- a/spring-cloud-data-flow/pom.xml +++ b/spring-cloud-data-flow/pom.xml @@ -1,11 +1,11 @@ 4.0.0 - org.baeldung.spring.cloud spring-cloud-data-flow 0.0.1-SNAPSHOT pom - + spring-cloud-data-flow + com.baeldung parent-modules diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index 4f31e55b96..e630df1865 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/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 - org.baeldung.spring.cloud time-processor 0.0.1-SNAPSHOT jar diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index dc593fdb14..649af32cf0 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/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 - org.baeldung.spring.cloud time-source 0.0.1-SNAPSHOT jar diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 16bc2d110a..eb2e46c3d0 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -15,18 +15,8 @@ ### Relevant Articles: - [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) -- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon) -- [A Quick Guide to Spring Cloud Consul](http://www.baeldung.com/spring-cloud-consul) -- [An Introduction to Spring Cloud Zookeeper](http://www.baeldung.com/spring-cloud-zookeeper) - [Using a Spring Cloud App Starter](http://www.baeldung.com/using-a-spring-cloud-app-starter) -- [Spring Cloud Connectors and Heroku](http://www.baeldung.com/spring-cloud-heroku) -- [An Example of Load Balancing with Zuul and Eureka](http://www.baeldung.com/zuul-load-balancing) -- [An Intro to Spring Cloud Contract](http://www.baeldung.com/spring-cloud-contract) - [Using a Spring Cloud App Starter](http://www.baeldung.com/spring-cloud-app-starter) - [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) -- [An Intro to Spring Cloud Security](http://www.baeldung.com/spring-cloud-security) -- [An Intro to Spring Cloud Task](http://www.baeldung.com/spring-cloud-task) - [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) -- [Introduction to Netflix Archaius with Spring Cloud](https://www.baeldung.com/netflix-archaius-spring-cloud-integration) -- [An Intro to Spring Cloud Vault](https://www.baeldung.com/spring-cloud-vault) -- [Netflix Archaius with Various Database Configurations](https://www.baeldung.com/netflix-archaius-database-configurations) + diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 28db4a7a3d..39cda888c5 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 diff --git a/spring-cloud/spring-cloud-archaius/README.md b/spring-cloud/spring-cloud-archaius/README.md index 9de26352e1..ae853c6ef0 100644 --- a/spring-cloud/spring-cloud-archaius/README.md +++ b/spring-cloud/spring-cloud-archaius/README.md @@ -1,3 +1,8 @@ +# Relevant Articles + +- [Introduction to Netflix Archaius with Spring Cloud](https://www.baeldung.com/netflix-archaius-spring-cloud-integration) +- [Netflix Archaius with Various Database Configurations](https://www.baeldung.com/netflix-archaius-database-configurations) + # Spring Cloud Archaius #### Basic Config @@ -11,4 +16,4 @@ These properties are set up on the main method, since Archaius uses System prope #### Additional Sources In this service we create a new AbstractConfiguration bean, setting up a new Configuration Properties source. -These properties have precedence over all the other properties in the Archaius Composite Configuration. \ No newline at end of file +These properties have precedence over all the other properties in the Archaius Composite Configuration. diff --git a/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml index 3ffbf8f619..96f6c8711e 100644 --- a/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml +++ b/spring-cloud/spring-cloud-archaius/dynamodb-config/pom.xml @@ -3,6 +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 dynamodb-config + dynamodb-config jar diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml index bb283576d8..59dea4890e 100644 --- a/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/pom.xml @@ -3,6 +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 jdbc-config + jdbc-config jar diff --git a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml index 8f8ec99ad8..51010eefb2 100644 --- a/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml +++ b/spring-cloud/spring-cloud-archaius/zookeeper-config/pom.xml @@ -3,6 +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 zookeeper-config + zookeeper-config jar diff --git a/spring-mustache/src/main/resources/application.properties b/spring-cloud/spring-cloud-aws/.attach_pid23938 similarity index 100% rename from spring-mustache/src/main/resources/application.properties rename to spring-cloud/spring-cloud-aws/.attach_pid23938 diff --git a/spring-cloud/spring-cloud-aws/README.md b/spring-cloud/spring-cloud-aws/README.md index 1340712c7a..36d0c7080e 100644 --- a/spring-cloud/spring-cloud-aws/README.md +++ b/spring-cloud/spring-cloud-aws/README.md @@ -1,5 +1,11 @@ # Spring Cloud AWS +# Relevant Articles +- [Spring Cloud AWS – S3](https://www.baeldung.com/spring-cloud-aws-s3) +- [Spring Cloud AWS – EC2](https://www.baeldung.com/spring-cloud-aws-ec2) +- [Spring Cloud AWS – RDS](https://www.baeldung.com/spring-cloud-aws-rds) +- [Spring Cloud AWS – Messaging Support](https://www.baeldung.com/spring-cloud-aws-messaging) + #### Running the Integration Tests To run the Integration Tests, we need to have an AWS account and have API keys generated for programmatic access. Edit @@ -23,4 +29,4 @@ Multiple application classes are available under this project. To launch Instan ``` com.baeldung.spring.cloud.aws.InstanceProfileAwsApplication -``` \ No newline at end of file +``` diff --git a/spring-cloud/spring-cloud-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml index 09518483a4..7edabd03f5 100644 --- a/spring-cloud/spring-cloud-aws/pom.xml +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -5,7 +5,7 @@ com.baeldung.spring.cloud spring-cloud-aws jar - Spring Cloud AWS + spring-cloud-aws Spring Cloud AWS Examples diff --git a/spring-cloud/spring-cloud-aws/src/test/resources/test-file-upload.txt b/spring-cloud/spring-cloud-aws/src/test/resources/test-file-upload.txt new file mode 100644 index 0000000000..7c4a013e52 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/resources/test-file-upload.txt @@ -0,0 +1 @@ +aaa \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml index 14a926fc2c..1379af0b05 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/config/pom.xml @@ -4,6 +4,7 @@ 4.0.0 config 1.0.0-SNAPSHOT + config parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml index f94d8829f6..735d3745d7 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - discovery 1.0.0-SNAPSHOT + discovery parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index fc69c16738..2efa926e3a 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -4,6 +4,7 @@ 4.0.0 gateway 1.0.0-SNAPSHOT + gateway parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/pom.xml b/spring-cloud/spring-cloud-bootstrap/pom.xml index 74801159eb..46460c0d74 100644 --- a/spring-cloud/spring-cloud-bootstrap/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/pom.xml @@ -4,6 +4,7 @@ 4.0.0 spring-cloud-bootstrap 1.0.0-SNAPSHOT + spring-cloud-bootstrap pom diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index c0d920d373..eb855a91e3 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - com.baeldung.spring.cloud svc-book 1.0.0-SNAPSHOT + svc-book parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml index 3aa2db8f65..7c1e93bad1 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - com.baeldung.spring.cloud svc-rating 1.0.0-SNAPSHOT + svc-rating parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml index 8735e24d48..1bf9ecb9e7 100644 --- a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml @@ -4,6 +4,7 @@ 4.0.0 zipkin 1.0.0-SNAPSHOT + zipkin parent-boot-1 diff --git a/spring-cloud/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml index 800a496a82..c55f9bc471 100644 --- a/spring-cloud/spring-cloud-config/client/pom.xml +++ b/spring-cloud/spring-cloud-config/client/pom.xml @@ -3,13 +3,14 @@ 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 - + client + client + com.baeldung.spring.cloud spring-cloud-config 1.0-SNAPSHOT - client diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml index b28828bf37..1a4efc7a60 100644 --- a/spring-cloud/spring-cloud-config/pom.xml +++ b/spring-cloud/spring-cloud-config/pom.xml @@ -5,6 +5,7 @@ com.baeldung.spring.cloud spring-cloud-config 1.0-SNAPSHOT + spring-cloud-config pom diff --git a/spring-cloud/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml index 7bbb903cf9..b4be7663e2 100644 --- a/spring-cloud/spring-cloud-config/server/pom.xml +++ b/spring-cloud/spring-cloud-config/server/pom.xml @@ -3,13 +3,14 @@ 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 - + server + server + com.baeldung.spring.cloud spring-cloud-config 1.0-SNAPSHOT - server diff --git a/spring-cloud/spring-cloud-connectors-heroku/README.md b/spring-cloud/spring-cloud-connectors-heroku/README.md new file mode 100644 index 0000000000..7c58d2526f --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Spring Cloud Connectors and Heroku](http://www.baeldung.com/spring-cloud-heroku) diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml index f00c9eb1fc..d2e9292511 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/pom.xml +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -5,6 +5,7 @@ com.baeldung.spring.cloud spring-cloud-connectors-heroku 1.0.0-SNAPSHOT + spring-cloud-connectors-heroku parent-boot-1 diff --git a/spring-cloud/spring-cloud-consul/README.md b/spring-cloud/spring-cloud-consul/README.md new file mode 100644 index 0000000000..47dc39f0d5 --- /dev/null +++ b/spring-cloud/spring-cloud-consul/README.md @@ -0,0 +1,3 @@ + +### Relevant Articles: +- [A Quick Guide to Spring Cloud Consul](http://www.baeldung.com/spring-cloud-consul) diff --git a/spring-cloud/spring-cloud-contract/README.md b/spring-cloud/spring-cloud-contract/README.md new file mode 100644 index 0000000000..70e056757b --- /dev/null +++ b/spring-cloud/spring-cloud-contract/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [An Intro to Spring Cloud Contract](http://www.baeldung.com/spring-cloud-contract) diff --git a/spring-cloud/spring-cloud-contract/pom.xml b/spring-cloud/spring-cloud-contract/pom.xml index 5dde6a7a99..3563d0ee58 100644 --- a/spring-cloud/spring-cloud-contract/pom.xml +++ b/spring-cloud/spring-cloud-contract/pom.xml @@ -6,6 +6,7 @@ com.baeldung.spring.cloud spring-cloud-contract 1.0.0-SNAPSHOT + spring-cloud-contract com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml index 7f7e2650d5..99d8c0ed40 100644 --- a/spring-cloud/spring-cloud-eureka/pom.xml +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -6,7 +6,7 @@ spring-cloud-eureka 1.0.0-SNAPSHOT pom - Spring Cloud Eureka + spring-cloud-eureka Spring Cloud Eureka Server and Sample Clients diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml index 0bf9547aff..5378095af0 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/pom.xml @@ -2,12 +2,10 @@ 4.0.0 - spring-cloud-eureka-client 1.0.0-SNAPSHOT jar - - Spring Cloud Eureka Client + spring-cloud-eureka-client Spring Cloud Eureka Sample Client diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml index d572b10d40..f2057c8a76 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/pom.xml @@ -5,7 +5,7 @@ spring-cloud-eureka-feign-client 1.0.0-SNAPSHOT jar - Spring Cloud Eureka Feign Client + spring-cloud-eureka-feign-client Spring Cloud Eureka - Sample Feign Client diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml index da2c50d3c7..587aed6c49 100644 --- a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/pom.xml @@ -5,7 +5,7 @@ spring-cloud-eureka-server 1.0.0-SNAPSHOT jar - Spring Cloud Eureka Server + spring-cloud-eureka-server Spring Cloud Eureka Server Demo diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index 8b2b0ad385..5686fc8c64 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -3,13 +3,11 @@ 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 - com.baeldung.spring - cloudfunction-aws + spring-cloud-functions 0.0.1-SNAPSHOT jar - - cloudfunction-aws + spring-cloud-functions Demo project for Spring Cloud Function diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 4d8b57d4cf..c297d90896 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -4,7 +4,7 @@ 4.0.0 spring-cloud-gateway jar - Spring Cloud Gateway + spring-cloud-gateway com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-kubernetes/README.md b/spring-cloud/spring-cloud-kubernetes/README.md new file mode 100644 index 0000000000..295ead1c2f --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Running Spring Boot Applications With Minikube](https://www.baeldung.com/spring-boot-minikube) diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml b/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml index 308a81fd74..f7b04baec3 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 demo-backend - + demo-backend + com.baeldung.spring.cloud spring-cloud-kubernetes diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml b/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml index 968529c648..da55ca5034 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 demo-frontend - + demo-frontend + com.baeldung.spring.cloud spring-cloud-kubernetes diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml new file mode 100644 index 0000000000..e963dafe67 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml @@ -0,0 +1,51 @@ + + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + + 4.0.0 + + liveness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/mongodb/Application.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java similarity index 89% rename from spring-boot/src/main/java/com/baeldung/mongodb/Application.java rename to spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java index 092ce3352b..2cfa242965 100644 --- a/spring-boot/src/main/java/com/baeldung/mongodb/Application.java +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java @@ -1,11 +1,12 @@ -package com.baeldung.mongodb; +package com.baeldung.liveness; 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); } -} +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..715c4cb178 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.liveness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = true; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = false; + }, 30, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/spring-5-reactive-functional/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml similarity index 100% rename from spring-5-reactive-functional/src/main/resources/logback.xml rename to spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..60b4a28aa6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.liveness.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 SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml new file mode 100644 index 0000000000..9fd3fd5674 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: liveness-example +spec: + selector: + app: liveness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: liveness-example +spec: + selector: + matchLabels: + app: liveness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: liveness-example + spec: + containers: + - name: liveness-example + image: dbdock/liveness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 10 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 1 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 20 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml new file mode 100644 index 0000000000..010c468107 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: readiness-example +spec: + selector: + app: readiness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: readiness-example +spec: + selector: + matchLabels: + app: readiness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: readiness-example + spec: + containers: + - name: readiness-example + image: dbdock/readiness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 40 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 5 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 100 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index fd9f7b5876..de0718633e 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -2,15 +2,17 @@ 4.0.0 - com.baeldung.spring.cloud spring-cloud-kubernetes 1.0-SNAPSHOT pom + spring-cloud-kubernetes demo-frontend demo-backend + liveness-example + readiness-example diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml new file mode 100644 index 0000000000..fa85120d21 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml @@ -0,0 +1,49 @@ + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + 4.0.0 + + readiness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java new file mode 100644 index 0000000000..11ffe577c3 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.readiness; + +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); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..d37a1905f6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.readiness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = false; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = true; + }, 40, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/spring-mustache/src/main/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml similarity index 100% rename from spring-mustache/src/main/resources/logback.xml rename to spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..18458182c7 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.readiness.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 SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-rest/README.md b/spring-cloud/spring-cloud-rest/README.md new file mode 100644 index 0000000000..a650004708 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/README.md @@ -0,0 +1,2 @@ + +Code for an ebook - "A REST API with Spring Boot and Spring Cloud" diff --git a/spring-cloud/spring-cloud-ribbon-client/README.md b/spring-cloud/spring-cloud-ribbon-client/README.md new file mode 100644 index 0000000000..596b3226c8 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Spring Cloud Rest Client with Netflix Ribbon](http://www.baeldung.com/spring-cloud-rest-client-with-netflix-ribbon) diff --git a/spring-cloud/spring-cloud-security/README.md b/spring-cloud/spring-cloud-security/README.md new file mode 100644 index 0000000000..7099406614 --- /dev/null +++ b/spring-cloud/spring-cloud-security/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [An Intro to Spring Cloud Security](http://www.baeldung.com/spring-cloud-security) diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 340c276c2d..5d15c6c726 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -5,8 +5,8 @@ auth-client jar auth-client - Spring Cloud Security APP Client Module - + Spring Cloud Security APP Client Module + spring-cloud-security com.baeldung @@ -61,6 +61,10 @@ org.springframework.boot spring-boot-starter-thymeleaf + + org.springframework.security.oauth + spring-security-oauth2 + diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 09474b2a4d..0367baa990 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 auth-resource @@ -14,16 +14,16 @@ com.baeldung 1.0.0-SNAPSHOT - + + + org.springframework.boot + spring-boot-starter-web + org.springframework.security.oauth spring-security-oauth2 - - org.springframework.cloud - spring-cloud-starter-security - org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index 92f92808f6..4b3f94b825 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -3,6 +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 auth-server + auth-server Spring Cloud Security APP Server Module diff --git a/spring-cloud/spring-cloud-task/README.md b/spring-cloud/spring-cloud-task/README.md new file mode 100644 index 0000000000..cabc1ac854 --- /dev/null +++ b/spring-cloud/spring-cloud-task/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [An Intro to Spring Cloud Task](http://www.baeldung.com/spring-cloud-task) diff --git a/spring-cloud/spring-cloud-task/pom.xml b/spring-cloud/spring-cloud-task/pom.xml index ef76d464bc..748cc378f1 100644 --- a/spring-cloud/spring-cloud-task/pom.xml +++ b/spring-cloud/spring-cloud-task/pom.xml @@ -6,6 +6,7 @@ spring-cloud-task 1.0.0-SNAPSHOT pom + spring-cloud-task parent-boot-1 diff --git a/spring-cloud/spring-cloud-vault/README.md b/spring-cloud/spring-cloud-vault/README.md new file mode 100644 index 0000000000..b7529b4a5c --- /dev/null +++ b/spring-cloud/spring-cloud-vault/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- [An Intro to Spring Cloud Vault](https://www.baeldung.com/spring-cloud-vault) + diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index 68b8e44875..363de6e107 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -1,87 +1,88 @@ - 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 - org.baeldung.spring.cloud - spring-cloud-vault - jar + org.baeldung.spring.cloud + spring-cloud-vault + jar - spring-cloud-vault - Demo project for Spring Boot + spring-cloud-vault + Demo project for Spring Boot - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + - + - - UTF-8 - UTF-8 - 1.8 - Finchley.SR1 - + + org.springframework.cloud + spring-cloud-starter-vault-config + - - - - - - - org.springframework.cloud - spring-cloud-starter-vault-config - + + org.springframework.cloud + spring-cloud-vault-config-databases + - - org.springframework.cloud - spring-cloud-vault-config-databases - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter-test - test - + + mysql + mysql-connector-java + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + - - mysql - mysql-connector-java - + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + spring-milestones + Spring Milestones + http://repo.spring.io/milestone + + false + + + - - org.springframework.boot - spring-boot-starter-jdbc - - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - + + UTF-8 + UTF-8 + 1.8 + Greenwich.M3 + diff --git a/spring-cloud/spring-cloud-zookeeper/README.md b/spring-cloud/spring-cloud-zookeeper/README.md new file mode 100644 index 0000000000..a639833452 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [An Introduction to Spring Cloud Zookeeper](http://www.baeldung.com/spring-cloud-zookeeper) diff --git a/spring-cloud/spring-cloud-zookeeper/pom.xml b/spring-cloud/spring-cloud-zookeeper/pom.xml index 4535c2072d..9661f2b71a 100644 --- a/spring-cloud/spring-cloud-zookeeper/pom.xml +++ b/spring-cloud/spring-cloud-zookeeper/pom.xml @@ -4,7 +4,8 @@ 4.0.0 spring-cloud-zookeeper pom - + spring-cloud-zookeeper + com.baeldung.spring.cloud spring-cloud diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/README.md b/spring-cloud/spring-cloud-zuul-eureka-integration/README.md new file mode 100644 index 0000000000..32074f3699 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [An Example of Load Balancing with Zuul and Eureka](http://www.baeldung.com/zuul-load-balancing) diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml index 6a5b7ddb55..c4f7ae704a 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/pom.xml @@ -5,7 +5,7 @@ eureka-client 1.0.0-SNAPSHOT jar - Spring Cloud Eureka Client + eureka-client Spring Cloud Eureka Sample Client diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml index e3c5109a26..0256ee7000 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/pom.xml @@ -5,7 +5,7 @@ eureka-server 1.0.0-SNAPSHOT jar - Spring Cloud Eureka Server + eureka-server Spring Cloud Eureka Server Demo diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml index 4d3687134f..edd7b9d99e 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/pom.xml @@ -7,7 +7,7 @@ spring-cloud-zuul-eureka-integration 1.0.0-SNAPSHOT pom - Spring Cloud Zuul and Eureka Integration + spring-cloud-zuul-eureka-integration Spring Cloud Zuul and Eureka Integration diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml index e64ceb501e..39f94efdf0 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/pom.xml @@ -2,6 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 zuul-server + zuul-server com.baeldung.spring.cloud diff --git a/spring-cloud/spring-cloud-zuul/README.md b/spring-cloud/spring-cloud-zuul/README.md new file mode 100644 index 0000000000..834917f159 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Rate Limiting in Spring Cloud Netflix Zuul](https://www.baeldung.com/spring-cloud-zuul-rate-limit) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 60f3262f08..f1e2e2a748 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -85,6 +85,7 @@ 1.16.12 2.5 1.5.2.RELEASE + 1.10.19 \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java index 38e8304f0f..a7a2a9032a 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -98,4 +98,18 @@ public class SpringResourceIntegrationTest { final String employees = new String(Files.readAllBytes(resource.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } + + @Test + public void whenClassPathResourceWithAbsoultePath_thenReadSuccessful() throws IOException { + final File resource = new ClassPathResource("/data/employees.dat", this.getClass()).getFile(); + final String employees = new String(Files.readAllBytes(resource.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenClassPathResourceWithRelativePath_thenReadSuccessful() throws IOException { + final File resource = new ClassPathResource("../../../data/employees.dat", SpringResourceIntegrationTest.class).getFile(); + final String employees = new String(Files.readAllBytes(resource.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } } diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index 64b543bb6c..2bc3201775 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -10,10 +10,10 @@ Demo project for Spring Boot - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index db94a86a6f..1624a3abfd 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -21,3 +21,4 @@ To view the running application, visit [http://localhost:8080](http://localhost: - [Projections and Excerpts in Spring Data REST](http://www.baeldung.com/spring-data-rest-projections-excerpts) - [Spring Data REST Events with @RepositoryEventHandler](http://www.baeldung.com/spring-data-rest-events) - [Customizing HTTP Endpoints in Spring Data REST](https://www.baeldung.com/spring-data-rest-customize-http-endpoints) +- [Spring Boot with SQLite](https://www.baeldung.com/spring-boot-sqlite) diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index a756ef0497..2fe4715bac 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -33,6 +33,15 @@ com.h2database h2 + + org.springframework.boot + spring-boot-autoconfigure + + + org.xerial + sqlite-jdbc + ${sqlite.version} + @@ -42,4 +51,10 @@ ${project.artifactId} + + com.baeldung.SpringDataRestApplication + 3.25.2 + 2.1.0.RELEASE + + diff --git a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java b/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java index 8d1f9de497..26d882d6a0 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java @@ -7,6 +7,7 @@ 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.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -14,11 +15,12 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -//@Configuration +@Configuration @EnableJpaRepositories(basePackages = "com.baeldung.repositories") // @PropertySource("persistence-h2.properties") // @PropertySource("persistence-hsqldb.properties") // @PropertySource("persistence-derby.properties") +//@PropertySource("persistence-sqlite.properties") public class DbConfig { @Autowired @@ -59,3 +61,25 @@ public class DbConfig { } } + +@Configuration +@Profile("h2") +@PropertySource("persistence-h2.properties") +class H2Config {} + +@Configuration +@Profile("hsqldb") +@PropertySource("persistence-hsqldb.properties") +class HsqldbConfig {} + + +@Configuration +@Profile("derby") +@PropertySource("persistence-derby.properties") +class DerbyConfig {} + + +@Configuration +@Profile("sqlite") +@PropertySource("persistence-sqlite.properties") +class SqliteConfig {} diff --git a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java b/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java new file mode 100644 index 0000000000..4512f7d34d --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java @@ -0,0 +1,78 @@ +package com.baeldung.dialect; + +import org.hibernate.dialect.Dialect; +import org.hibernate.dialect.identity.IdentityColumnSupport; + +import java.sql.Types; + +public class SQLiteDialect extends Dialect { + + public SQLiteDialect() { + registerColumnType(Types.BIT, "integer"); + registerColumnType(Types.TINYINT, "tinyint"); + registerColumnType(Types.SMALLINT, "smallint"); + registerColumnType(Types.INTEGER, "integer"); + registerColumnType(Types.BIGINT, "bigint"); + registerColumnType(Types.FLOAT, "float"); + registerColumnType(Types.REAL, "real"); + registerColumnType(Types.DOUBLE, "double"); + registerColumnType(Types.NUMERIC, "numeric"); + registerColumnType(Types.DECIMAL, "decimal"); + registerColumnType(Types.CHAR, "char"); + registerColumnType(Types.VARCHAR, "varchar"); + registerColumnType(Types.LONGVARCHAR, "longvarchar"); + registerColumnType(Types.DATE, "date"); + registerColumnType(Types.TIME, "time"); + registerColumnType(Types.TIMESTAMP, "timestamp"); + registerColumnType(Types.BINARY, "blob"); + registerColumnType(Types.VARBINARY, "blob"); + registerColumnType(Types.LONGVARBINARY, "blob"); + registerColumnType(Types.BLOB, "blob"); + registerColumnType(Types.CLOB, "clob"); + registerColumnType(Types.BOOLEAN, "integer"); + } + + public IdentityColumnSupport getIdentityColumnSupport() { + return new SQLiteIdentityColumnSupport(); + } + + public boolean hasAlterTable() { + return false; + } + + public boolean dropConstraints() { + return false; + } + + public String getDropForeignKeyString() { + return ""; + } + + public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) { + return ""; + } + + public String getAddPrimaryKeyConstraintString(String constraintName) { + return ""; + } + + public String getForUpdateString() { + return ""; + } + + public String getAddColumnString() { + return "add column"; + } + + public boolean supportsOuterJoinForUpdate() { + return false; + } + + public boolean supportsIfExistsBeforeTableName() { + return true; + } + + public boolean supportsCascadeDelete() { + return false; + } +} diff --git a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java b/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java new file mode 100644 index 0000000000..cf6e3a9a97 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java @@ -0,0 +1,22 @@ +package com.baeldung.dialect; + +import org.hibernate.MappingException; +import org.hibernate.dialect.identity.IdentityColumnSupportImpl; + +public class SQLiteIdentityColumnSupport extends IdentityColumnSupportImpl { + + @Override + public boolean supportsIdentityColumns() { + return true; + } + + @Override + public String getIdentitySelectString(String table, String column, int type) throws MappingException { + return "select last_insert_rowid()"; + } + + @Override + public String getIdentityColumnString(int type) throws MappingException { + return "integer"; + } +} diff --git a/spring-data-rest/src/main/resources/application.properties b/spring-data-rest/src/main/resources/application.properties index e69de29bb2..06cb22a4fe 100644 --- a/spring-data-rest/src/main/resources/application.properties +++ b/spring-data-rest/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.profiles.default=h2 \ No newline at end of file diff --git a/spring-data-rest/src/main/resources/persistence-sqlite.properties b/spring-data-rest/src/main/resources/persistence-sqlite.properties index 018c2cbaca..b6b5f4e4d6 100644 --- a/spring-data-rest/src/main/resources/persistence-sqlite.properties +++ b/spring-data-rest/src/main/resources/persistence-sqlite.properties @@ -1,4 +1,7 @@ driverClassName=org.sqlite.JDBC -url=jdbc:sqlite:memory:myDb +url=jdbc:sqlite:memory:myDb?cache=shared username=sa -password=sa \ No newline at end of file +password=sa +hibernate.dialect=com.baeldung.dialect.SQLiteDialect +hibernate.hbm2ddl.auto=create-drop +hibernate.show_sql=true diff --git a/spring-drools/pom.xml b/spring-drools/pom.xml index 8c65d5e34e..5bb2d6a8e9 100644 --- a/spring-drools/pom.xml +++ b/spring-drools/pom.xml @@ -5,7 +5,8 @@ com.baeldung spring-drools 1.0.0-SNAPSHOT - + spring-drools + com.baeldung parent-modules diff --git a/spring-ejb/spring-ejb-remote/pom.xml b/spring-ejb/spring-ejb-remote/pom.xml index 4756846cc8..797cc3ac68 100644 --- a/spring-ejb/spring-ejb-remote/pom.xml +++ b/spring-ejb/spring-ejb-remote/pom.xml @@ -4,7 +4,8 @@ 4.0.0 spring-ejb-remote ejb - + spring-ejb-remote + com.baeldung.spring.ejb spring-ejb diff --git a/spring-ejb/wildfly/pom.xml b/spring-ejb/wildfly/pom.xml index 8f7d4c287a..f50dad82f1 100644 --- a/spring-ejb/wildfly/pom.xml +++ b/spring-ejb/wildfly/pom.xml @@ -2,10 +2,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT pom - wildfly-example + wildfly com.baeldung.spring.ejb diff --git a/spring-ejb/wildfly/widlfly-web/pom.xml b/spring-ejb/wildfly/widlfly-web/pom.xml index 559c5f1755..f0baac10dd 100644 --- a/spring-ejb/wildfly/widlfly-web/pom.xml +++ b/spring-ejb/wildfly/widlfly-web/pom.xml @@ -3,10 +3,11 @@ 4.0.0 widlfly-web war - + widlfly-web + com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT diff --git a/spring-ejb/wildfly/wildfly-ear/pom.xml b/spring-ejb/wildfly/wildfly-ear/pom.xml index d1e47ecd0f..93d6df96e5 100644 --- a/spring-ejb/wildfly/wildfly-ear/pom.xml +++ b/spring-ejb/wildfly/wildfly-ear/pom.xml @@ -3,10 +3,11 @@ 4.0.0 wildfly-ear ear - + wildfly-ear + com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT diff --git a/spring-ejb/wildfly/wildfly-ejb-interfaces/pom.xml b/spring-ejb/wildfly/wildfly-ejb-interfaces/pom.xml index ec502f2ab3..41c7012ea9 100644 --- a/spring-ejb/wildfly/wildfly-ejb-interfaces/pom.xml +++ b/spring-ejb/wildfly/wildfly-ejb-interfaces/pom.xml @@ -2,10 +2,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 wildfly-ejb-interfaces - + wildfly-ejb-interfaces + com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT diff --git a/spring-ejb/wildfly/wildfly-ejb/pom.xml b/spring-ejb/wildfly/wildfly-ejb/pom.xml index 2c87ec8449..12bfc9c1bf 100644 --- a/spring-ejb/wildfly/wildfly-ejb/pom.xml +++ b/spring-ejb/wildfly/wildfly-ejb/pom.xml @@ -3,10 +3,11 @@ 4.0.0 wildfly-ejb ejb - + wildfly-ejb + com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT diff --git a/spring-ejb/wildfly/wildfly-jpa/pom.xml b/spring-ejb/wildfly/wildfly-jpa/pom.xml index 12cf2c81e4..3005ab714c 100644 --- a/spring-ejb/wildfly/wildfly-jpa/pom.xml +++ b/spring-ejb/wildfly/wildfly-jpa/pom.xml @@ -2,10 +2,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 wildfly-jpa - + wildfly-jpa + com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT diff --git a/spring-ejb/wildfly/wildfly-mdb/pom.xml b/spring-ejb/wildfly/wildfly-mdb/pom.xml index 186ddc50c0..a2ffca2fc5 100644 --- a/spring-ejb/wildfly/wildfly-mdb/pom.xml +++ b/spring-ejb/wildfly/wildfly-mdb/pom.xml @@ -6,7 +6,7 @@ com.baeldung.wildfly - wildfly-example + wildfly 0.0.1-SNAPSHOT diff --git a/spring-freemarker/pom.xml b/spring-freemarker/pom.xml index 4ff57e27f0..02f2a3fd06 100644 --- a/spring-freemarker/pom.xml +++ b/spring-freemarker/pom.xml @@ -5,7 +5,7 @@ spring-freemarker war 1.0-SNAPSHOT - Spring Freemarker Example + spring-freemarker com.baeldung diff --git a/spring-integration/README.md b/spring-integration/README.md index e116f934c8..244cf1fb14 100644 --- a/spring-integration/README.md +++ b/spring-integration/README.md @@ -2,6 +2,7 @@ - [Introduction to Spring Integration](http://www.baeldung.com/spring-integration) - [Security In Spring Integration](http://www.baeldung.com/spring-integration-security) - [Spring Integration Java DSL](https://www.baeldung.com/spring-integration-java-dsl) +- [Using Subflows in Spring Integration](https://www.baeldung.com/spring-integration-subflows) ### Running the Sample Executing the `mvn exec:java` maven command (either from the command line or from an IDE) will start up the application. Follow the command prompt for further instructions. diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index 457645a144..8a5399ae0b 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -104,14 +104,6 @@ - - - repo.springsource.org.milestone - Spring Framework Maven Milestone Repository - https://repo.springsource.org/milestone - - - UTF-8 5.0.3.RELEASE diff --git a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 8eb1589de7..0354f7211c 100644 --- a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -3,12 +3,14 @@ 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 SpringContextIntegrationTest { @Test diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 872835177d..b548de3701 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -6,7 +6,8 @@ spring-jersey 0.1-SNAPSHOT war - + spring-jersey + com.baeldung parent-modules @@ -100,12 +101,12 @@ com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider - 2.6.0 + 2.9.7 com.fasterxml.jackson.core jackson-databind - 2.6.0 + 2.9.7 org.slf4j diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index 744ae34cc8..8bce500a86 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -2,12 +2,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jooq - + spring-jooq + - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -128,6 +129,9 @@ com.baeldung.jooq.introduction.db src/main/java + + + @@ -184,14 +188,12 @@ - 3.8.6 + 3.11.7 1.4.193 - 4.3.17.RELEASE 1.0.0 1.5 1.0.0 - 1.5.13.RELEASE org.jooq.example.spring.Application diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 3060dc00b3..5c370880b4 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -8,10 +8,10 @@ Intro to Kafka with Spring - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -30,12 +30,11 @@ com.fasterxml.jackson.core jackson-databind - 1.1.3.RELEASE - 2.6.7 + 2.9.7 \ No newline at end of file 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 50978d5ea9..4ee7f40335 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 @@ -22,7 +22,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); /* @@ -102,7 +102,7 @@ public class KafkaApplication { } public void sendMessageToPartion(String message, int partition) { - kafkaTemplate.send(partionedTopicName, partition, message); + kafkaTemplate.send(partionedTopicName, partition, null, message); } public void sendMessageToFiltered(String message) { @@ -124,13 +124,13 @@ public class KafkaApplication { private CountDownLatch greetingLatch = new CountDownLatch(1); - @KafkaListener(topics = "${message.topic.name}", group = "foo", containerFactory = "fooKafkaListenerContainerFactory") + @KafkaListener(topics = "${message.topic.name}", groupId = "foo", containerFactory = "fooKafkaListenerContainerFactory") public void listenGroupFoo(String message) { System.out.println("Received Messasge in group 'foo': " + message); latch.countDown(); } - @KafkaListener(topics = "${message.topic.name}", group = "bar", containerFactory = "barKafkaListenerContainerFactory") + @KafkaListener(topics = "${message.topic.name}", groupId = "bar", containerFactory = "barKafkaListenerContainerFactory") public void listenGroupBar(String message) { System.out.println("Received Messasge in group 'bar': " + message); latch.countDown(); diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java similarity index 90% rename from spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java index 40bf86c76f..b8195633fd 100644 --- a/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java @@ -9,7 +9,7 @@ import com.baeldung.spring.kafka.KafkaApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = KafkaApplication.class) -public class SpringContextIntegrationTest { +public class SpringContextManualTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 39648a982c..756aae93d3 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -5,7 +5,8 @@ spring-katharsis 0.0.1-SNAPSHOT war - + spring-katharsis + parent-boot-1 com.baeldung diff --git a/spring-ldap/README.md b/spring-ldap/README.md index e2517b9d4b..b8163ab44d 100644 --- a/spring-ldap/README.md +++ b/spring-ldap/README.md @@ -3,8 +3,4 @@ ### Relevant articles - [Spring LDAP Overview](http://www.baeldung.com/spring-ldap) -- [Spring LDAP Example Project](http://www.baeldung.com/spring-ldap-overview/) - [Guide to Spring Data LDAP](http://www.baeldung.com/spring-data-ldap) - - - diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 3b2525d899..7399a84c2b 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -5,6 +5,7 @@ spring-ldap 0.1-SNAPSHOT jar + spring-ldap com.baeldung diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index d65820594f..4b04c3b8d5 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -32,20 +32,4 @@ - - - spring-releases - Spring Milestone Repository - https://repo.spring.io/libs-release - - - - - - spring-releases - Spring Milestone Repository - https://repo.spring.io/libs-release - - - diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index d1fa7f410e..481c818f39 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -11,10 +11,10 @@ Injecting Mockito Mocks into Spring Beans - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-mockito/src/test/java/com/baeldung/NameServiceTestConfiguration.java b/spring-mockito/src/test/java/com/baeldung/NameServiceTestConfiguration.java index 2c63ff6203..c50377a22a 100644 --- a/spring-mockito/src/test/java/com/baeldung/NameServiceTestConfiguration.java +++ b/spring-mockito/src/test/java/com/baeldung/NameServiceTestConfiguration.java @@ -11,7 +11,7 @@ import org.springframework.context.annotation.Profile; public class NameServiceTestConfiguration { @Bean @Primary - public NameService nameService() { + public NameService nameServiceTest() { return Mockito.mock(NameService.class); } } diff --git a/spring-mustache/.gitignore b/spring-mustache/.gitignore deleted file mode 100644 index 2af7cefb0a..0000000000 --- a/spring-mustache/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/spring-mustache/README.md b/spring-mustache/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/spring-mustache/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/spring-mustache/pom.xml b/spring-mustache/pom.xml deleted file mode 100644 index 9e4c528ee0..0000000000 --- a/spring-mustache/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - - spring-mustache - jar - spring-mustache - Demo project for Spring Boot - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-mustache - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.webjars - bootstrap - ${bootstrap.version} - - - org.fluttercode.datafactory - datafactory - ${datafactory.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - 3.3.7 - 0.8 - - - diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java deleted file mode 100644 index 8cdf89d08a..0000000000 --- a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.springmustache; - -import com.samskivert.mustache.Mustache; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.core.env.Environment; - -@SpringBootApplication -@ComponentScan(basePackages = {"com.baeldung"}) -public class SpringMustacheApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringMustacheApplication.class, args); - } - - @Bean - public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader templateLoader, Environment environment) { - - MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); - collector.setEnvironment(environment); - - return Mustache.compiler() - .defaultValue("Some Default Value") - .withLoader(templateLoader) - .withCollector(collector); - - } -} - diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java deleted file mode 100644 index 5fc34c9f07..0000000000 --- a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.springmustache.controller; - -import com.baeldung.springmustache.model.Article; -import org.fluttercode.datafactory.impl.DataFactory; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.servlet.ModelAndView; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -@Controller -public class ArticleController { - - @GetMapping("/article") - public ModelAndView displayArticle(Map model) { - - List
articles = IntStream.range(0, 10) - .mapToObj(i -> generateArticle("Article Title " + i)) - .collect(Collectors.toList()); - - Map modelMap = new HashMap<>(); - modelMap.put("articles", articles); - - return new ModelAndView("index", modelMap); - } - - private Article generateArticle(String title) { - Article article = new Article(); - DataFactory factory = new DataFactory(); - article.setTitle(title); - article.setBody( - "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus."); - article.setPublishDate(factory.getBirthDate().toString()); - article.setAuthor(factory.getName()); - return article; - } -} - - diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java b/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java deleted file mode 100644 index 78b08f877f..0000000000 --- a/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.springmustache.model; - -public class Article { - private String title; - private String body; - private String author; - private String publishDate; - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public String getPublishDate() { - return publishDate; - } - - public void setPublishDate(String publishDate) { - this.publishDate = publishDate; - } - -} diff --git a/spring-mustache/src/main/resources/templates/error/error.html b/spring-mustache/src/main/resources/templates/error/error.html deleted file mode 100644 index fa29db41c4..0000000000 --- a/spring-mustache/src/main/resources/templates/error/error.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - Something went wrong: {{status}} {{error}} - - - \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/index.html b/spring-mustache/src/main/resources/templates/index.html deleted file mode 100644 index bda60f9d8f..0000000000 --- a/spring-mustache/src/main/resources/templates/index.html +++ /dev/null @@ -1,9 +0,0 @@ -{{>layout/header}} - -
{{>layout/article}}
- - - - -{{>layout/footer}} diff --git a/spring-mustache/src/main/resources/templates/layout/article.html b/spring-mustache/src/main/resources/templates/layout/article.html deleted file mode 100644 index 9d573580d3..0000000000 --- a/spring-mustache/src/main/resources/templates/layout/article.html +++ /dev/null @@ -1,8 +0,0 @@ -
- {{#articles}} -

{{title}}

-

{{publishDate}}

-

{{author}}

-

{{body}}

- {{/articles}} -
\ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/footer.html b/spring-mustache/src/main/resources/templates/layout/footer.html deleted file mode 100644 index 04f34cac54..0000000000 --- a/spring-mustache/src/main/resources/templates/layout/footer.html +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/header.html b/spring-mustache/src/main/resources/templates/layout/header.html deleted file mode 100644 index d203ef800b..0000000000 --- a/spring-mustache/src/main/resources/templates/layout/header.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java deleted file mode 100644 index 1eecf58986..0000000000 --- a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationIntegrationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.springmustache; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class SpringMustacheApplicationIntegrationTest { - - @Autowired - private TestRestTemplate restTemplate; - - @Test - public void givenIndexPageWhenContainsArticleThenTrue() { - - ResponseEntity entity = this.restTemplate.getForEntity("/article", String.class); - - Assert.assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); - Assert.assertTrue(entity.getBody().contains("Article Title 0")); - } - -} diff --git a/spring-mvc-forms-thymeleaf/README.md b/spring-mvc-forms-thymeleaf/README.md index f0f7e35a98..22f12afbca 100644 --- a/spring-mvc-forms-thymeleaf/README.md +++ b/spring-mvc-forms-thymeleaf/README.md @@ -2,3 +2,4 @@ - [Session Attributes in Spring MVC](http://www.baeldung.com/spring-mvc-session-attributes) - [Binding a List in Thymeleaf](http://www.baeldung.com/thymeleaf-list) + diff --git a/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeConfig.java b/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeConfig.java new file mode 100644 index 0000000000..8a5d1c71af --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.datetime; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; +import org.springframework.format.number.NumberFormatAnnotationFormatterFactory; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.format.support.FormattingConversionService; + +import java.time.format.DateTimeFormatter; + +@Configuration +class DateTimeConfig { + + @Bean + public FormattingConversionService conversionService() { + DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false); + + conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory()); + + DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); + registrar.setDateFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy")); + registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")); + registrar.registerFormatters(conversionService); + + return conversionService; + } + +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeController.java b/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeController.java new file mode 100644 index 0000000000..5741b35530 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/datetime/DateTimeController.java @@ -0,0 +1,29 @@ +package com.baeldung.datetime; + +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; + +@RestController +public class DateTimeController { + + @PostMapping("/date") + public void date(@RequestParam("date") @DateTimeFormat(pattern = "dd.MM.yyyy") Date date) { + // ... + } + + @PostMapping("/localdate") + public void localDate(@RequestParam("localDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate localDate) { + // ... + } + + @PostMapping("/localdatetime") + public void dateTime(@RequestParam("localDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime localDateTime) { + // ... + } +} \ No newline at end of file diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md index a9b002afd7..755e0932fc 100644 --- a/spring-mvc-simple/README.md +++ b/spring-mvc-simple/README.md @@ -7,3 +7,4 @@ - [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles) - [Guide to Spring Email](http://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) diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index e4e30183eb..65fa4339d6 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -4,8 +4,7 @@ spring-mvc-simple war 0.0.1-SNAPSHOT - Spring MVC simple Maven Webapp - http://maven.apache.org + spring-mvc-simple com.baeldung @@ -197,7 +196,7 @@ 1.2.5 1.0.2 1.9.0 - 2.9.4 + 2.9.7 1.4.9 5.1.0 20180130 diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 442a533d1b..3199118281 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -8,7 +8,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial) - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) - [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) - [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 7187b5c270..8e4a56c148 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung 0.1-SNAPSHOT spring-mvc-xml @@ -86,13 +85,13 @@ - + - org.springframework.boot - spring-boot-starter-test - 1.5.10.RELEASE - test - + org.springframework.boot + spring-boot-starter-test + 1.5.10.RELEASE + test + @@ -116,14 +115,6 @@ - - - 1 - jstl - https://mvnrepository.com/artifact/javax.servlet/jstl - - - diff --git a/spring-mybatis/README.md b/spring-mybatis/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/spring-mybatis/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/spring-mybatis/pom.xml b/spring-mybatis/pom.xml deleted file mode 100644 index 7b8b66fef1..0000000000 --- a/spring-mybatis/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - 4.0.0 - com.baeldung - spring-mybatis - jar - 0.0.1-SNAPSHOT - spring-mybatis Maven Webapp - http://maven.apache.org - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.mybatis - mybatis - ${mybatis.version} - - - org.mybatis - mybatis-spring - ${mybatis-spring.version} - - - org.springframework - spring-context-support - ${spring.version} - - - org.springframework - spring-test - ${spring.version} - test - - - mysql - mysql-connector-java - ${mysql-connector.version} - - - javax.servlet - jstl - ${jstl.version} - - - org.springframework - spring-webmvc - ${spring-webmvc.version} - - - javax.servlet - servlet-api - ${servlet.version} - - - - - spring-mybatis - - - - 3.1.1 - 1.1.1 - 3.1.1.RELEASE - 3.2.4.RELEASE - 5.1.40 - 1.2 - 2.5 - - diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/application/SpringMyBatisApplication.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/application/SpringMyBatisApplication.java deleted file mode 100644 index acfaff2669..0000000000 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/application/SpringMyBatisApplication.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.spring.mybatis.application; - -import java.util.Date; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.baeldung.spring.mybatis.model.Student; -import com.baeldung.spring.mybatis.service.StudentService; - -public class SpringMyBatisApplication { - - public static void main(String[] args){ - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("mybatis-spring.xml"); - - StudentService studentService = (StudentService) ctx.getBean("studentService"); - Student student = new Student(); - student.setFirstName("Santosh"); - student.setLastName("B S"); - student.setEmailAddress("santosh.bse@gmail.com"); - student.setPassword("Test123"); - student.setDateOfBirth(new Date()); - student.setUserName("santoshbs1"); - - boolean result = studentService.insertStudent(student); - if(result){ - System.out.println("Student record saved successfully"); - } - else{ - System.out.println("Encountered an error while saving student data"); - } - - final String userName = "santosh"; - Student matchingStudent = studentService.getStudentByUserName(userName); - if(matchingStudent == null){ - System.out.println("No matching student found for User Name - " + userName); - } - else{ - System.out.println("Student Details are as follows : "); - System.out.println("First Name : " + matchingStudent.getFirstName()); - System.out.println("Last Name : " + matchingStudent.getLastName()); - System.out.println("EMail : " + matchingStudent.getEmailAddress()); - System.out.println("DOB : " + matchingStudent.getDateOfBirth()); - System.out.println("User Name : " + matchingStudent.getUserName()); - } - - } - -} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java deleted file mode 100644 index c1e5579103..0000000000 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/controller/StudentController.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.spring.mybatis.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.ui.ModelMap; -import org.springframework.validation.BindingResult; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.SessionAttributes; - -import com.baeldung.spring.mybatis.model.Student; -import com.baeldung.spring.mybatis.model.StudentLogin; -import com.baeldung.spring.mybatis.service.StudentService; - -@Controller -@SessionAttributes("student") -public class StudentController { - - @Autowired - private StudentService studentService; - - @RequestMapping(value = "/signup", method = RequestMethod.GET) - public String signup(Model model) { - Student student = new Student(); - model.addAttribute("student", student); - return "signup"; - } - - @RequestMapping(value = "/signup", method = RequestMethod.POST) - public String signup(@Validated @ModelAttribute("student") Student student, BindingResult result, ModelMap model) { - if (studentService.getStudentByUserName(student.getUserName()) != null) { - model.addAttribute("message", "User Name exists. Try another user name"); - return "signup"; - } else { - studentService.insertStudent(student); - model.addAttribute("message", "Saved student details"); - return "redirect:login.html"; - } - } - - @RequestMapping(value = "/login", method = RequestMethod.GET) - public String login(Model model) { - StudentLogin studentLogin = new StudentLogin(); - model.addAttribute("studentLogin", studentLogin); - return "login"; - } - - @RequestMapping(value = "/login", method = RequestMethod.POST) - public String login(@ModelAttribute("studentLogin") StudentLogin studentLogin, BindingResult result, ModelMap model) { - boolean found = studentService.getStudentByLogin(studentLogin.getUserName(), studentLogin.getPassword()) != null; - if (found) { - return "success"; - } else { - return "failure"; - } - } -} \ No newline at end of file diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/mappers/StudentMapper.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/mappers/StudentMapper.java deleted file mode 100644 index cf3584f7b1..0000000000 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/mappers/StudentMapper.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.spring.mybatis.mappers; - -import org.apache.ibatis.annotations.Insert; -import org.apache.ibatis.annotations.Options; -import org.apache.ibatis.annotations.Select; - -import com.baeldung.spring.mybatis.model.Student; - -public interface StudentMapper { - @Insert("INSERT INTO student(userName, password, firstName,lastName, dateOfBirth, emailAddress) VALUES" - + "(#{userName},#{password}, #{firstName}, #{lastName}, #{dateOfBirth}, #{emailAddress})") - @Options(useGeneratedKeys = true, keyProperty = "id", flushCache = true, keyColumn = "id") - public void insertStudent(Student student); - - @Select("SELECT USERNAME as userName, PASSWORD as password, FIRSTNAME as firstName, LASTNAME as lastName, " - + "DATEOFBIRTH as dateOfBirth, EMAILADDRESS as emailAddress " + "FROM student WHERE userName = #{userName}") - public Student getStudentByUserName(String userName); - -} \ No newline at end of file diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/Student.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/Student.java deleted file mode 100644 index f33dd44f72..0000000000 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/Student.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.spring.mybatis.model; - -import java.util.Date; - -public class Student { - private Long id; - private String userName; - private String firstName; - private String lastName; - private String password; - private String emailAddress; - private Date dateOfBirth; - 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 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 getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public String getEmailAddress() { - return emailAddress; - } - public void setEmailAddress(String emailAddress) { - this.emailAddress = emailAddress; - } - public Date getDateOfBirth() { - return dateOfBirth; - } - public void setDateOfBirth(Date dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } -} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/StudentLogin.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/StudentLogin.java deleted file mode 100644 index 867857b510..0000000000 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/model/StudentLogin.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.spring.mybatis.model; - -public class StudentLogin { - private String userName; - private String password; - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } -} diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentService.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentService.java deleted file mode 100644 index d26115beee..0000000000 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.spring.mybatis.service; - -import com.baeldung.spring.mybatis.model.Student; - -public interface StudentService { - public boolean insertStudent(Student student); - public Student getStudentByLogin(String userName, String password); - public Student getStudentByUserName(String userName); -} \ No newline at end of file diff --git a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentServiceImpl.java b/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentServiceImpl.java deleted file mode 100644 index 538e650482..0000000000 --- a/spring-mybatis/src/main/java/com/baeldung/spring/mybatis/service/StudentServiceImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.spring.mybatis.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.spring.mybatis.mappers.StudentMapper; -import com.baeldung.spring.mybatis.model.Student; - -@Service("studentService") -public class StudentServiceImpl implements StudentService { - - @Autowired - private StudentMapper studentMapper; - - @Transactional - public boolean insertStudent(Student student) { - boolean result=false; - try{ - studentMapper.insertStudent(student); - result = true; - } - catch(Exception ex){ - ex.printStackTrace(); - result = false; - } - return result; - } - - public Student getStudentByLogin(String userName, String password) { - Student student = studentMapper.getStudentByUserName(userName); - return student; - } - - public Student getStudentByUserName(String userName) { - Student student = studentMapper.getStudentByUserName(userName); - return student; - } - -} diff --git a/spring-mybatis/src/main/resources/mybatis-spring.xml b/spring-mybatis/src/main/resources/mybatis-spring.xml deleted file mode 100644 index 9f5bab3247..0000000000 --- a/spring-mybatis/src/main/resources/mybatis-spring.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/conf/mybatis-spring.xml b/spring-mybatis/src/main/webapp/WEB-INF/conf/mybatis-spring.xml deleted file mode 100644 index c8b686358c..0000000000 --- a/spring-mybatis/src/main/webapp/WEB-INF/conf/mybatis-spring.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp deleted file mode 100644 index 66f16d4e09..0000000000 --- a/spring-mybatis/src/main/webapp/WEB-INF/jsp/failure.jsp +++ /dev/null @@ -1,36 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> - - - - - -Login Failure - - - - -
- Login     Signup -
-
-
-

Student Enrollment Login failure

-
-
-
- - Oh snap! Something is wrong. Change a few things up - and try submitting again. -
-
-
-
-
- - ">Try - again? - - \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp deleted file mode 100644 index 5a895bb348..0000000000 --- a/spring-mybatis/src/main/webapp/WEB-INF/jsp/login.jsp +++ /dev/null @@ -1,81 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> - - - - - - - -Student Login - - -
- Login     Signup -
- -
-
-
-

Welcome to Online Student Enrollment Application

-

Login to explore the complete features!

-
-
- -
-
- -
-
- Student Enrollment Login Form - - - - - - - - - - - - - - - -
-
- -      - -
- -
-
-
- - - - \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp deleted file mode 100644 index bc628862f3..0000000000 --- a/spring-mybatis/src/main/webapp/WEB-INF/jsp/signup.jsp +++ /dev/null @@ -1,130 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> -<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> - - - - - -Student Signup - - - - - -
- Login     Signup -
- -
-
-
-

Welcome to Online Student Enrollment Application

-

Login to explore the complete features!

-
-
- -
-
- -
- -
${message}
-
-
- -
- -
- Student Enrollment Signup Form - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
- -     - -
-
-
-
- - \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp b/spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp deleted file mode 100644 index 7ae37bc241..0000000000 --- a/spring-mybatis/src/main/webapp/WEB-INF/jsp/success.jsp +++ /dev/null @@ -1,35 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> - - - - -Login Success - - - - -
- Login     Signup -
- -
-
-

Student Enrollment Login success

-
-
-
- - Well done! You successfully logged-into the system. - Now you can explore the complete features! -
-
-
-
-
- ">Login - as different user? - - \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.40-bin.jar b/spring-mybatis/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.40-bin.jar deleted file mode 100644 index 60bef5cfbf..0000000000 Binary files a/spring-mybatis/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.1.40-bin.jar and /dev/null differ diff --git a/spring-mybatis/src/main/webapp/WEB-INF/web.xml b/spring-mybatis/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 569b5ef9b1..0000000000 --- a/spring-mybatis/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - myBatisSpringServlet - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - /WEB-INF/conf/mybatis-spring.xml - - - - - myBatisSpringServlet - *.html - - - MyBatis-Spring Integration - \ No newline at end of file diff --git a/spring-mybatis/src/main/webapp/index.jsp b/spring-mybatis/src/main/webapp/index.jsp deleted file mode 100644 index b60222e7de..0000000000 --- a/spring-mybatis/src/main/webapp/index.jsp +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - -
- Login     Signup -
- -
-
-
-

Welcome to Online Student Enrollment Application

-

Login to explore the complete features!

-
-
- -
-
- - - \ No newline at end of file diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 1ab5048d27..372f969bd7 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -7,10 +7,10 @@ spring-protobuf - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -36,21 +36,10 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - - 3.1.0 1.4 + com.baeldung.protobuf.Application
diff --git a/spring-protobuf/src/main/java/com/baeldung/protobuf/Application.java b/spring-protobuf/src/main/java/com/baeldung/protobuf/Application.java index 76f0e45244..fd36986549 100644 --- a/spring-protobuf/src/main/java/com/baeldung/protobuf/Application.java +++ b/spring-protobuf/src/main/java/com/baeldung/protobuf/Application.java @@ -1,22 +1,28 @@ package com.baeldung.protobuf; -import com.baeldung.protobuf.BaeldungTraining.Course; -import com.baeldung.protobuf.BaeldungTraining.Student; -import com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber; -import com.baeldung.protobuf.BaeldungTraining.Student.PhoneType; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; -import org.springframework.web.client.RestTemplate; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +import com.baeldung.protobuf.BaeldungTraining.Course; +import com.baeldung.protobuf.BaeldungTraining.Student; +import com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber; +import com.baeldung.protobuf.BaeldungTraining.Student.PhoneType; + @SpringBootApplication public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } @Bean RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) { diff --git a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java index 4b9f41ace3..f0e2473ec4 100644 --- a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java +++ b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java @@ -16,12 +16,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.ResponseEntity; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import com.baeldung.protobuf.BaeldungTraining.Course; import com.googlecode.protobuf.format.JsonFormat; +@DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) public class ApplicationIntegrationTest { diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 615ebd5f4a..6d021eb400 100644 --- a/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -3,10 +3,12 @@ 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.protobuf.Application; +@DirtiesContext @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class SpringContextIntegrationTest { diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 47ffeccba9..77424c219e 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -11,10 +11,10 @@ Demo project for Scheduling in Spring with Quartz - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml index bff39984e0..7bd31396f7 100644 --- a/spring-reactive-kotlin/pom.xml +++ b/spring-reactive-kotlin/pom.xml @@ -4,7 +4,7 @@ 4.0.0 spring-reactive-kotlin jar - Spring Reactive Kotlin + spring-reactive-kotlin Demo project for Spring Boot diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index f6db404656..c6ad99aea7 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -9,10 +9,10 @@ http://maven.apache.org - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -27,26 +27,12 @@ io.projectreactor reactor-bus + 2.0.8.RELEASE + + + io.projectreactor + reactor-core + 2.0.8.RELEASE - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/libs-snapshot - - true - - - - - - - spring-releases - Spring Releases - https://repo.spring.io/libs-release - - - diff --git a/spring-reactor/src/main/java/com/baeldung/controller/NotificationController.java b/spring-reactor/src/main/java/com/baeldung/controller/NotificationController.java index b17691498e..8665f247b0 100644 --- a/spring-reactor/src/main/java/com/baeldung/controller/NotificationController.java +++ b/spring-reactor/src/main/java/com/baeldung/controller/NotificationController.java @@ -1,14 +1,16 @@ package com.baeldung.controller; -import com.baeldung.doman.NotificationData; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.doman.NotificationData; + import reactor.bus.Event; import reactor.bus.EventBus; -@Controller +@RestController public class NotificationController { @Autowired diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index 9f05bc91d2..060f33837c 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -7,13 +7,14 @@ pom 1.0-SNAPSHOT spring-remoting - Parent for all projects related to Spring Remoting. + Parent for all projects related to Spring Remoting, except remoting-hessian-burlap + - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -28,8 +29,8 @@ - remoting-http remoting-hessian-burlap + remoting-http remoting-amqp remoting-jms remoting-rmi diff --git a/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextManualTest.java similarity index 90% rename from spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextManualTest.java index 5dc6d1df75..a6ee0b6000 100644 --- a/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-remoting/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextManualTest.java @@ -9,7 +9,7 @@ import com.baeldung.server.AmqpServer; @RunWith(SpringRunner.class) @SpringBootTest(classes = AmqpServer.class) -public class SpringContextIntegrationTest { +public class SpringContextManualTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml index 6cb5a51812..8c30e76296 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -5,11 +5,14 @@ 4.0.0 remoting-hessian-burlap pom + remoting-hessian-burlap + 1.0-SNAPSHOT - spring-remoting + parent-boot-1 com.baeldung - 1.0-SNAPSHOT + 0.0.1-SNAPSHOT + ../../parent-boot-1 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 f337d5e51f..104712c3d7 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 @@ -2,15 +2,16 @@ - + 4.0.0 + spring-remoting-hessian-burlap-client + spring-remoting-hessian-burlap-client + + remoting-hessian-burlap com.baeldung 1.0-SNAPSHOT - 4.0.0 - - spring-remoting-hessian-burlap-client - + org.springframework.boot diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml index 5b6e03348f..33b824442f 100644 --- a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml @@ -2,14 +2,15 @@ + 4.0.0 + remoting-hessian-burlap-server + remoting-hessian-burlap-server + remoting-hessian-burlap com.baeldung 1.0-SNAPSHOT - 4.0.0 - - remoting-hessian-burlap-server diff --git a/spring-remoting/remoting-http/pom.xml b/spring-remoting/remoting-http/pom.xml index 3262736ec8..886a28b886 100644 --- a/spring-remoting/remoting-http/pom.xml +++ b/spring-remoting/remoting-http/pom.xml @@ -4,8 +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 remoting-http - Parent for all modules related to HTTP Spring Remoting. pom + + remoting-http + Parent for all modules related to HTTP Spring Remoting. com.baeldung diff --git a/spring-remoting/remoting-http/remoting-http-client/pom.xml b/spring-remoting/remoting-http/remoting-http-client/pom.xml index 9a6e98ffdd..56412d3cdf 100644 --- a/spring-remoting/remoting-http/remoting-http-client/pom.xml +++ b/spring-remoting/remoting-http/remoting-http-client/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 remoting-http-client + remoting-http-client Shows how to invoke a remote service using Spring Remoting HTTP. diff --git a/spring-remoting/remoting-http/remoting-http-server/pom.xml b/spring-remoting/remoting-http/remoting-http-server/pom.xml index 53d27a5efa..c3f87e776e 100644 --- a/spring-remoting/remoting-http/remoting-http-server/pom.xml +++ b/spring-remoting/remoting-http/remoting-http-server/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 remoting-http-server + remoting-http-server Shows how to expose a service using Spring Remoting HTTP. diff --git a/spring-remoting/remoting-jms/pom.xml b/spring-remoting/remoting-jms/pom.xml index fe36431423..e24b5b7929 100644 --- a/spring-remoting/remoting-jms/pom.xml +++ b/spring-remoting/remoting-jms/pom.xml @@ -2,18 +2,20 @@ + 4.0.0 + remoting-jms + remoting-jms + pom + spring-remoting com.baeldung 1.0-SNAPSHOT - 4.0.0 - pom + remoting-jms-client remoting-jms-server - remoting-jms - \ No newline at end of file diff --git a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml index ed27282a38..b7b1af5a1a 100644 --- a/spring-remoting/remoting-jms/remoting-jms-client/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-client/pom.xml @@ -2,14 +2,15 @@ + 4.0.0 + remoting-jms-client + remoting-jms-client + remoting-jms com.baeldung 1.0-SNAPSHOT - 4.0.0 - - remoting-jms-client UTF-8 diff --git a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml index 7657267f1d..8a17cdb0a9 100644 --- a/spring-remoting/remoting-jms/remoting-jms-server/pom.xml +++ b/spring-remoting/remoting-jms/remoting-jms-server/pom.xml @@ -2,14 +2,15 @@ + 4.0.0 + remoting-jms-server + remoting-jms-server + remoting-jms com.baeldung 1.0-SNAPSHOT - 4.0.0 - - remoting-jms-server UTF-8 diff --git a/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextManualTest.java similarity index 90% rename from spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextManualTest.java index 5c9cc5f872..b806f21c27 100644 --- a/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-remoting/remoting-jms/remoting-jms-server/src/test/java/org/baeldung/SpringContextManualTest.java @@ -9,7 +9,7 @@ import com.baeldung.server.JmsServer; @SpringBootTest(classes = JmsServer.class) @RunWith(SpringRunner.class) -public class SpringContextIntegrationTest { +public class SpringContextManualTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-remoting/remoting-rmi/pom.xml b/spring-remoting/remoting-rmi/pom.xml index cd15a6ec60..b3b84786b8 100644 --- a/spring-remoting/remoting-rmi/pom.xml +++ b/spring-remoting/remoting-rmi/pom.xml @@ -3,8 +3,9 @@ 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 - pom remoting-rmi + pom + remoting-rmi spring-remoting diff --git a/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml b/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml index 1e3cd4b977..4ac0283e94 100644 --- a/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml +++ b/spring-remoting/remoting-rmi/remoting-rmi-client/pom.xml @@ -2,15 +2,16 @@ + 4.0.0 + remoting-rmi-client + remoting-rmi-client + remoting-rmi com.baeldung 1.0-SNAPSHOT - 4.0.0 - - remoting-rmi-client - + org.springframework.boot diff --git a/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextLiveTest.java similarity index 90% rename from spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextLiveTest.java index 3460792fc6..3bace4cd1e 100644 --- a/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-remoting/remoting-rmi/remoting-rmi-client/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -9,7 +9,7 @@ import com.baeldung.client.RmiClient; @SpringBootTest(classes = RmiClient.class) @RunWith(SpringRunner.class) -public class SpringContextIntegrationTest { +public class SpringContextLiveTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml index 68b01829e1..7fb4d2c1bc 100644 --- a/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/pom.xml @@ -2,14 +2,15 @@ + 4.0.0 + remoting-rmi-server + remoting-rmi-server + remoting-rmi com.baeldung 1.0-SNAPSHOT - 4.0.0 - - remoting-rmi-server UTF-8 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 index d6fe719311..fd10643c53 100644 --- 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 @@ -6,12 +6,12 @@ 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.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication @EnableAutoConfiguration @Import(PersistenceConfig.class) -public class Application extends WebMvcConfigurerAdapter { +public class Application implements WebMvcConfigurer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java index 4d65c02fff..1473d44b92 100644 --- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java @@ -1,62 +1,66 @@ package org.baeldung.web.service; +import static io.restassured.RestAssured.given; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsCollectionContaining.hasItems; +import static org.hamcrest.core.IsEqual.equalTo; + import org.apache.commons.lang3.RandomStringUtils; import org.baeldung.web.main.Application; import org.junit.Test; 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.test.context.junit4.SpringRunner; -import static io.restassured.RestAssured.given; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.hamcrest.core.IsEqual.equalTo; - @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class StudentServiceIntegrationTest { + + @LocalServerPort + int port; - private static final String ENDPOINT = "http://localhost:8080/student/get"; + private static final String ENDPOINT = "http://localhost:%s/student/get"; @Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat() + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat() .body("content.name", hasItems("Bryan", "Ben")); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectTwoItems() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("size", equalTo(2)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("size", equalTo(2)); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("numberOfElements", equalTo(2)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("numberOfElements", equalTo(2)); } @Test public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().statusCode(200); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(200); } @Test public void givenRequestForStudents_whenPageOfResourcesAreRetrievedOutOfBounds_thenExpect500() { - given().params("page", "1000", "size", "2").get(ENDPOINT).then().statusCode(500); + given().params("page", "1000", "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageNotValid_thenExpect500() { - given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT).then().statusCode(500); + given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageSizeIsFive_expectFiveItems() { - given().params("page", "0", "size", "5").get(ENDPOINT).then().body("content.size()", is(5)); + given().params("page", "0", "size", "5").get(String.format(ENDPOINT, port)).then().body("content.size()", is(5)); } @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("first", equalTo(true)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("first", equalTo(true)); } } diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml deleted file mode 100644 index a8c53dbc3a..0000000000 --- a/spring-rest-embedded-tomcat/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - 4.0.0 - org.baeldung.embedded - spring-rest-embedded-tomcat - spring-rest-embedded-tomcat - war - - - com.baeldung - parent-spring-5 - 0.0.1-SNAPSHOT - ../parent-spring-5 - - - - - org.springframework - spring-webmvc - ${spring.version} - - - - javax.servlet - javax.servlet-api - ${servlet.version} - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.library} - - - - org.apache.tomcat.embed - tomcat-embed-core - ${tomcat.version} - test - - - - org.apache.tomcat - tomcat-jasper - ${tomcat.version} - test - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - org.apache.httpcomponents - httpcore - ${httpcore.version} - - - - org.springframework.boot - spring-boot-starter-test - 1.5.10.RELEASE - test - - - - - - 2.9.2 - 4.0.0 - 9.0.1 - 4.5.3 - 4.4.8 - false - - - \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java deleted file mode 100644 index 24bd28166b..0000000000 --- a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.embedded.configuration; - -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; - -public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return new Class[] { UserConfiguration.class }; - } - - @Override - protected Class[] getServletConfigClasses() { - return null; - } - - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } - -} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java deleted file mode 100644 index 4c102a74cb..0000000000 --- a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung.embedded.configuration; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = "org.baeldung.embedded") -public class UserConfiguration { - -} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java deleted file mode 100644 index a9a5faa0c6..0000000000 --- a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.baeldung.embedded.controller; - -import org.baeldung.embedded.domain.User; -import org.baeldung.embedded.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; -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.RestController; - -@RestController -public class UserController { - - @Autowired - UserService userService; - - @RequestMapping("/") - public String welcome() { - return "Hello World!"; - } - - @RequestMapping(method = RequestMethod.GET, value = "/user/{userName}") - @ResponseBody - public User user(@PathVariable String userName) { - return this.userService.getUser(userName); - } -} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java deleted file mode 100644 index 2f9443daea..0000000000 --- a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.embedded.domain; - -public class User { - - private String name; - private String hobby; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getHobby() { - return hobby; - } - - public void setHobby(String hobby) { - this.hobby = hobby; - } -} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java deleted file mode 100644 index 76696e12c2..0000000000 --- a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.baeldung.embedded.service; - -import java.util.ArrayList; -import java.util.List; - -import org.baeldung.embedded.domain.User; -import org.springframework.stereotype.Service; - -@Service -public class UserService { - private List users = new ArrayList<>(); - - public void addUser(String name) { - User user = new User(); - user.setName(name); - if (name == "HarryPotter") { - user.setHobby("Quidditch"); - } else { - user.setHobby("MuggleActivity"); - } - users.add(user); - } - - public User getUser(String name) { - for (User user : users) { - if (user.getName() - .equalsIgnoreCase(name)) { - return user; - } - } - - User user = new User(); - user.setName(name); - user.setHobby("None"); - - return user; - } -} diff --git a/spring-rest-embedded-tomcat/src/main/webapp/emptyFile b/spring-rest-embedded-tomcat/src/main/webapp/emptyFile deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 8b8ff1a322..0000000000 --- a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.embedded.configuration.UserConfiguration; -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 = { UserConfiguration.class }) -@WebAppConfiguration -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java deleted file mode 100644 index f340f6c837..0000000000 --- a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.baeldung.embedded; - -import java.io.File; -import java.util.concurrent.CountDownLatch; -import org.apache.catalina.Context; -import org.apache.catalina.startup.Tomcat; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - -public class EmbeddedTomcatApp { - - private Tomcat tomcatInstance; - private WebApplicationContext webApplicationContext; - private CountDownLatch started = new CountDownLatch(1); - - public void start() throws Exception { - tomcatInstance = new Tomcat(); - tomcatInstance.setBaseDir(new File(getClass().getResource(".") - .toURI()).getAbsolutePath()); // Tomcat's temporary directory - tomcatInstance.setPort(0); - - Context webapp = tomcatInstance.addWebapp("", new File("src/main/webapp/").getAbsolutePath()); - - webapp.addLifecycleListener(event -> { - if (event.getType() - .equals("after_stop")) { - started.countDown(); - } else if (event.getType() - .equals("after_start")) { - webApplicationContext = WebApplicationContextUtils - .findWebApplicationContext(webapp.getServletContext()); - - ((ConfigurableListableBeanFactory) webApplicationContext - .getAutowireCapableBeanFactory()).registerSingleton("baseUrl", getBaseUrl()); - - started.countDown(); - } - }); - - tomcatInstance.start(); - started.await(); - } - - public Tomcat getTomcatInstance() { - return this.tomcatInstance; - } - - public String getBaseUrl() { - return String.format("http://localhost:%d%s", getLocalPort(), getWebApplicationContext().getServletContext() - .getContextPath()); - } - - public int getLocalPort() { - return tomcatInstance.getConnector() - .getLocalPort(); - } - - public WebApplicationContext getWebApplicationContext() { - return webApplicationContext; - } - - public boolean isStarted() { - return started.getCount() == 0; - } - - public boolean isStartedSucessfully() { - return webApplicationContext != null; - } -} diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java deleted file mode 100644 index 1bf15556e8..0000000000 --- a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.embedded; - -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; - -public class EmbeddedTomcatRunner extends BlockJUnit4ClassRunner { - - public EmbeddedTomcatRunner(Class klass) throws InitializationError { - super(klass); - } - - // use one static Tomcat instance shared across all tests - private static EmbeddedTomcatApp embeddedTomcatApp = new EmbeddedTomcatApp(); - - @Override - protected Statement classBlock(RunNotifier notifier) { - ensureSharedTomcatStarted(); - Statement result = super.classBlock(notifier); - return result; - } - - private void ensureSharedTomcatStarted() { - if (!embeddedTomcatApp.isStarted()) { - try { - embeddedTomcatApp.start(); - } catch (Exception e) { - throw new RuntimeException("Error while starting embedded Tomcat server", e); - } - } - } - - @Override - protected Object createTest() throws Exception { - if (!embeddedTomcatApp.isStartedSucessfully()) { - throw new RuntimeException("Tomcat server not started successfully. Skipping test"); - } - Object testInstance = super.createTest(); - embeddedTomcatApp.getWebApplicationContext() - .getAutowireCapableBeanFactory() - .autowireBean(testInstance); - return testInstance; - } -} \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java deleted file mode 100644 index 1c5d482171..0000000000 --- a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.baeldung.embedded; - -import java.io.IOException; -import java.util.Map; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -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.baeldung.embedded.service.UserService; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(EmbeddedTomcatRunner.class) -public class UserIntegrationTest { - - @Autowired - protected String baseUrl; - - @Autowired - private UserService userService; - - private String userName = "HarryPotter"; - - @Before - public void setUp() { - userService.addUser(userName); - } - - @Test - public void givenUserName_whenSendGetForHarryPotter_thenHobbyQuidditch() throws IOException { - String url = baseUrl + "/user/" + userName; - - HttpClient httpClient = HttpClientBuilder.create() - .build(); - HttpGet getUserRequest = new HttpGet(url); - getUserRequest.addHeader("Content-type", "application/json"); - HttpResponse response = httpClient.execute(getUserRequest); - - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine() - .getStatusCode()); - - HttpEntity responseEntity = response.getEntity(); - - Assert.assertNotNull(responseEntity); - - ObjectMapper mapper = new ObjectMapper(); - String retSrc = EntityUtils.toString(responseEntity); - Map result = mapper.readValue(retSrc, Map.class); - - Assert.assertEquals("Quidditch", result.get("hobby")); - } -} diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index b8fef9cb82..d429e17671 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -17,9 +17,9 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) -- [Build a REST API with Spring 4 and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) +- [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) - [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) - +- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) ### Build the Project diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml index 6c56faf0b2..ee0a2c043d 100644 --- a/spring-rest-hal-browser/pom.xml +++ b/spring-rest-hal-browser/pom.xml @@ -3,10 +3,11 @@ 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 - com.baeldung spring-rest-hal-browser 1.0-SNAPSHOT + spring-rest-hal-browser + diff --git a/spring-rest-template/README.md b/spring-rest-template/README.md deleted file mode 100644 index d69d5c01c7..0000000000 --- a/spring-rest-template/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Spring REST Template Example Project - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: -- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) diff --git a/spring-rest-template/checkstyle.xml b/spring-rest-template/checkstyle.xml deleted file mode 100644 index 85063a7570..0000000000 --- a/spring-rest-template/checkstyle.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/spring-rest-template/pom.xml b/spring-rest-template/pom.xml deleted file mode 100644 index fa93308cf5..0000000000 --- a/spring-rest-template/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - 4.0.0 - com.baeldung - spring-rest-template - 0.1-SNAPSHOT - spring-rest-template - jar - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - - - spring-rest-template - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - check - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - - - - 3.0.0 - - diff --git a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java deleted file mode 100644 index 804013d4dc..0000000000 --- a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.web.upload.client; - -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -public class MultipartFileUploadClient { - - public static void main(String[] args) throws IOException { - uploadSingleFile(); - uploadMultipleFile(); - } - - private static void uploadSingleFile() throws IOException { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - MultiValueMap body = new LinkedMultiValueMap<>(); - body.add("file", getTestFile()); - - - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); - System.out.println("Response code: " + response.getStatusCode()); - } - - private static void uploadMultipleFile() throws IOException { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - MultiValueMap body = new LinkedMultiValueMap<>(); - body.add("files", getTestFile()); - body.add("files", getTestFile()); - body.add("files", getTestFile()); - - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); - System.out.println("Response code: " + response.getStatusCode()); - } - - public static Resource getTestFile() throws IOException { - Path testFile = Files.createTempFile("test-file", ".txt"); - System.out.println("Creating and Uploading Test File: " + testFile); - Files.write(testFile, "Hello World !!, This is a test file.".getBytes()); - return new FileSystemResource(testFile.toFile()); - } - -} diff --git a/spring-rest/README.md b/spring-rest/README.md index d449a4d92a..4921ab012c 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -6,7 +6,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Http Message Converters with the Spring Framework](http://www.baeldung.com/spring-httpmessageconverter-rest) -- [Redirect in Spring](http://www.baeldung.com/spring-redirect-and-forward) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) - [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) - [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) @@ -15,7 +14,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Custom Media Type for a Spring REST API](http://www.baeldung.com/spring-rest-custom-media-type) - [HTTP PUT vs HTTP PATCH in a REST API](http://www.baeldung.com/http-put-patch-difference-spring) - [Spring – Log Incoming Requests](http://www.baeldung.com/spring-http-logging) -- [RequestBody and ResponseBody Annotations](http://www.baeldung.com/requestbody-and-responsebody-annotations) - [Introduction to CheckStyle](http://www.baeldung.com/checkstyle-java) - [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port) - [Guide to DeferredResult in Spring](http://www.baeldung.com/spring-deferred-result) @@ -23,3 +21,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using the Spring RestTemplate Interceptor](http://www.baeldung.com/spring-rest-template-interceptor) - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) +- [Spring’s RequestBody and ResponseBody Annotations](https://www.baeldung.com/spring-request-response-body) +- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index ba74d26c35..5c88697cef 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -183,9 +183,6 @@ org.springframework.boot spring-boot-maven-plugin - - true - org.apache.maven.plugins @@ -300,6 +297,7 @@ 2.2.0 3.5.11 3.1.0 + com.baeldung.sampleapp.config.MainApplication diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java similarity index 90% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java index baaa4c4d80..1967d4f2aa 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists; +package com.baeldung.resttemplate.lists; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java similarity index 86% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index 729fa3ca3e..191719b084 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -1,11 +1,12 @@ -package org.baeldung.resttemplate.lists.client; +package com.baeldung.resttemplate.lists.client; -import org.baeldung.resttemplate.lists.dto.Employee; -import org.baeldung.resttemplate.lists.dto.EmployeeList; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; +import com.baeldung.resttemplate.lists.dto.Employee; +import com.baeldung.resttemplate.lists.dto.EmployeeList; + import java.util.ArrayList; import java.util.List; @@ -42,7 +43,7 @@ public class EmployeeClient ResponseEntity> response = restTemplate.exchange( - "http://localhost:8080/spring-rest/employees/", + "http://localhost:8082/spring-rest/employees/", HttpMethod.GET, null, new ParameterizedTypeReference>(){}); @@ -60,7 +61,7 @@ public class EmployeeClient EmployeeList response = restTemplate.getForObject( - "http://localhost:8080/spring-rest/employees/v2", + "http://localhost:8082/spring-rest/employees/v2", EmployeeList.class); List employees = response.getEmployees(); @@ -79,7 +80,7 @@ public class EmployeeClient newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8080/spring-rest/employees/", + "http://localhost:8082/spring-rest/employees/", newEmployees, ResponseEntity.class); } @@ -93,7 +94,7 @@ public class EmployeeClient newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8080/spring-rest/employees/v2/", + "http://localhost:8082/spring-rest/employees/v2/", new EmployeeList(newEmployees), ResponseEntity.class); } diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java index f051c6a78b..8a4d510f63 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java @@ -1,14 +1,15 @@ -package org.baeldung.resttemplate.lists.controller; +package com.baeldung.resttemplate.lists.controller; -import org.baeldung.resttemplate.lists.dto.Employee; -import org.baeldung.resttemplate.lists.dto.EmployeeList; -import org.baeldung.resttemplate.lists.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.resttemplate.lists.dto.Employee; +import com.baeldung.resttemplate.lists.dto.EmployeeList; +import com.baeldung.resttemplate.lists.service.EmployeeService; + import java.util.List; @RestController diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java similarity index 92% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java index bd8ebbf969..0754c13c5b 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists.dto; +package com.baeldung.resttemplate.lists.dto; public class Employee { diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java similarity index 91% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java index 2bb86ac5b4..eeabbfe450 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java @@ -1,4 +1,4 @@ -package org.baeldung.resttemplate.lists.dto; +package com.baeldung.resttemplate.lists.dto; import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java rename to spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java index 08196dda77..226134787f 100644 --- a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java @@ -1,8 +1,9 @@ -package org.baeldung.resttemplate.lists.service; +package com.baeldung.resttemplate.lists.service; -import org.baeldung.resttemplate.lists.dto.Employee; import org.springframework.stereotype.Service; +import com.baeldung.resttemplate.lists.dto.Employee; + import java.util.ArrayList; import java.util.List; diff --git a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/config/MainApplication.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java index 6a7fdc041a..507f340e9d 100644 --- a/spring-rest/src/main/java/org/baeldung/config/MainApplication.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableAutoConfiguration -@ComponentScan("org.baeldung") +@ComponentScan("com.baeldung.sampleapp") public class MainApplication implements WebMvcConfigurer { public static void main(final String[] args) { diff --git a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java index 8743af20fe..8abc368bdb 100644 --- a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java @@ -1,15 +1,16 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import java.util.ArrayList; import java.util.List; -import org.baeldung.interceptors.RestTemplateHeaderModifierInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.util.CollectionUtils; import org.springframework.web.client.RestTemplate; +import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor; + @Configuration public class RestClientConfig { diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java similarity index 95% rename from spring-rest/src/main/java/org/baeldung/config/WebConfig.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java index b3e3cd179a..d5209a520b 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.sampleapp.config; import java.text.SimpleDateFormat; import java.util.List; @@ -18,7 +18,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; */ @Configuration @EnableWebMvc -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.sampleapp.web" }) public class WebConfig implements WebMvcConfigurer { public WebConfig() { diff --git a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java b/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java similarity index 91% rename from spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java index fabb904634..519e5ebf0d 100644 --- a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java @@ -1,4 +1,4 @@ -package org.baeldung.interceptors; +package com.baeldung.sampleapp.interceptors; import java.io.IOException; diff --git a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java b/spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java similarity index 72% rename from spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java index e4eb6d8875..ea9541c31a 100644 --- a/spring-rest/src/main/java/org/baeldung/repository/HeavyResourceRepository.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java @@ -1,10 +1,10 @@ -package org.baeldung.repository; - -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; +package com.baeldung.sampleapp.repository; import java.util.Map; +import com.baeldung.sampleapp.web.dto.HeavyResource; +import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly; + public class HeavyResourceRepository { public void save(HeavyResource heavyResource) { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java similarity index 96% rename from spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java index 1c3a1086ca..c6b8d23944 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java similarity index 82% rename from spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java index aa694c08ed..bfda2fe0d6 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/CompanyController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java @@ -1,10 +1,11 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; -import org.baeldung.web.dto.Company; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.Company; + @RestController public class CompanyController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java similarity index 98% rename from spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java index 5d039d2d02..8f4eb3218a 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/DeferredResultController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java similarity index 88% rename from spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java index fed45066bd..8156fc14a9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/HeavyResourceController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java @@ -1,11 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Map; -import org.baeldung.repository.HeavyResourceRepository; -import org.baeldung.web.dto.HeavyResource; -import org.baeldung.web.dto.HeavyResourceAddressOnly; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -14,6 +11,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.repository.HeavyResourceRepository; +import com.baeldung.sampleapp.web.dto.HeavyResource; +import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly; + @RestController public class HeavyResourceController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java index 1cc3eae432..69bd458968 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java @@ -1,14 +1,14 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Date; -import org.baeldung.web.dto.Item; -import org.baeldung.web.dto.ItemManager; -import org.baeldung.web.dto.Views; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.Item; +import com.baeldung.sampleapp.web.dto.ItemManager; +import com.baeldung.sampleapp.web.dto.Views; import com.fasterxml.jackson.annotation.JsonView; @RestController diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 251e0b23e7..11ea5b70c9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/MyFooController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.Collection; import java.util.HashMap; @@ -6,8 +6,6 @@ import java.util.Map; import javax.servlet.http.HttpServletResponse; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.exception.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -18,6 +16,9 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import com.baeldung.sampleapp.web.dto.Foo; +import com.baeldung.sampleapp.web.exception.ResourceNotFoundException; + @Controller @RequestMapping(value = "/foos") public class MyFooController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/PactController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java similarity index 90% rename from spring-rest/src/main/java/org/baeldung/web/controller/PactController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java index 4f586479ef..0f5d7f1acb 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/PactController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java @@ -1,9 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.util.ArrayList; import java.util.List; -import org.baeldung.web.dto.PactDto; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -12,6 +11,8 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.sampleapp.web.dto.PactDto; + @RestController public class PactController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java similarity index 97% rename from spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java index f8407acb47..7b57d35088 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/SimplePostController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.sampleapp.web.controller; import java.io.BufferedOutputStream; import java.io.File; @@ -7,7 +7,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import org.baeldung.web.dto.Foo; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -15,6 +14,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import com.baeldung.sampleapp.web.dto.Foo; + // used to test HttpClientPostingTest @RestController public class SimplePostController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java similarity index 85% rename from spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java index a0a6c6341e..fc73bade87 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/mediatypes/CustomMediaTypeController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java @@ -1,13 +1,14 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.sampleapp.web.controller.mediatypes; -import org.baeldung.web.dto.BaeldungItem; -import org.baeldung.web.dto.BaeldungItemV2; 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.RestController; +import com.baeldung.sampleapp.web.dto.BaeldungItem; +import com.baeldung.sampleapp.web.dto.BaeldungItemV2; + @RestController @RequestMapping(value = "/", produces = "application/vnd.baeldung.api.v1+json") public class CustomMediaTypeController { diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java similarity index 98% rename from spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java index 59868593a3..321f3be3ef 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/redirect/RedirectController.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.redirect; +package com.baeldung.sampleapp.web.controller.redirect; import javax.servlet.http.HttpServletRequest; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java similarity index 83% rename from spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java index 9b3ecd33b9..807a254cfc 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItem.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class BaeldungItem { private final String itemId; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java similarity index 84% rename from spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java index 64df20a14e..f84591ea43 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/BaeldungItemV2.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class BaeldungItemV2 { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/Company.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java index 3164d604ad..6cfcc079d9 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Company.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class Company { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java index 240b368b50..186df8e678 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java similarity index 96% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java index 934e76606f..2821341888 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResource.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResource { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java index f96347d60c..01ee6e7dd4 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressOnly.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressOnly { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java index f90f02ea08..1832a1a58b 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/HeavyResourceAddressPartialUpdate.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class HeavyResourceAddressPartialUpdate { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Item.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java similarity index 94% rename from spring-rest/src/main/java/org/baeldung/web/dto/Item.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java index 536c72020f..a4fcef5dce 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Item.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; import com.fasterxml.jackson.annotation.JsonView; diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java similarity index 80% rename from spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java index 74ffada300..0009c0180b 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/ItemManager.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class ItemManager { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java similarity index 93% rename from spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java index e34e2bdf3b..e184119611 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/PactDto.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class PactDto { diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/Views.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java similarity index 75% rename from spring-rest/src/main/java/org/baeldung/web/dto/Views.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java index 6231e12bcc..e2d83fda22 100644 --- a/spring-rest/src/main/java/org/baeldung/web/dto/Views.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.sampleapp.web.dto; public class Views { public static class Public { diff --git a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java similarity index 82% rename from spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java rename to spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java index aab737b6ec..69532f196d 100644 --- a/spring-rest/src/main/java/org/baeldung/web/exception/ResourceNotFoundException.java +++ b/spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.exception; +package com.baeldung.sampleapp.web.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java similarity index 79% rename from spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java rename to spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java index d6821196eb..f3b1c0dc6f 100644 --- a/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java +++ b/spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java @@ -9,9 +9,9 @@ import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan("com.baeldung.web.upload") @SpringBootApplication -public class Application extends SpringBootServletInitializer { +public class UploadApplication extends SpringBootServletInitializer { public static void main(final String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(UploadApplication.class, args); } } \ No newline at end of file diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java deleted file mode 100644 index 996f229128..0000000000 --- a/spring-rest/src/main/java/org/baeldung/web/controller/advice/JsonpControllerAdvice.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.web.controller.advice; - -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; - -@ControllerAdvice -public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - - public JsonpControllerAdvice() { - super("callback"); - } - -} diff --git a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml index 7e7d820836..ddb9c91792 100644 --- a/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml +++ b/spring-rest/src/main/webapp/WEB-INF/api-servlet.xml @@ -6,7 +6,7 @@ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" > - + diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index 1b8b767ae3..20a11f3422 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -16,7 +16,7 @@ contextConfigLocation - org.baeldung.config + com.baeldung.sampleapp.config 19.0 3.5 - 2.9.4 + 2.9.7 2.6 diff --git a/spring-security-mvc-persisted-remember-me/README.md b/spring-security-mvc-persisted-remember-me/README.md index f910c3f62b..e505537be1 100644 --- a/spring-security-mvc-persisted-remember-me/README.md +++ b/spring-security-mvc-persisted-remember-me/README.md @@ -7,9 +7,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me) -- [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me) -- [Redirect to different pages after Login with Spring Security](http://www.baeldung.com/spring_redirect_after_login) - ### Build the Project ``` diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index d1b8365077..b83f10d9fe 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -188,7 +188,7 @@ 1.11.3.RELEASE 1.4.196 1.2.3 - 2.8.7 + 2.9.7 \ No newline at end of file diff --git a/spring-security-openid/src/main/resources/application.properties.sample.properties b/spring-security-openid/src/main/resources/application.properties similarity index 100% rename from spring-security-openid/src/main/resources/application.properties.sample.properties rename to spring-security-openid/src/main/resources/application.properties diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index d9b6a760b2..f71eead9ae 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -15,6 +15,4 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Context Propagation with @Async](http://www.baeldung.com/spring-security-async-principal-propagation) - [Servlet 3 Async Support with Spring MVC and Spring Security](http://www.baeldung.com/spring-mvc-async-security) - [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) -- [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) -- [Error Handling for REST with Spring 3](http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/) - [Spring Security for a REST API](http://www.baeldung.com/securing-a-restful-web-service-with-spring-security) diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index ef16f2201b..37c743e896 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -281,7 +281,7 @@ 3.1.0 1.1.0.Final 1.2 - 2.9.2 + 2.9.7 26.0-jre diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 7761919ca7..4b297a91b5 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -23,6 +23,8 @@ 3.1.0 + 2.3.3.RELEASE + 2.1.1.RELEASE - \ No newline at end of file + diff --git a/spring-security-sso/spring-security-sso-auth-server/pom.xml b/spring-security-sso/spring-security-sso-auth-server/pom.xml index c0ad6dee2e..ff76f377c6 100644 --- a/spring-security-sso/spring-security-sso-auth-server/pom.xml +++ b/spring-security-sso/spring-security-sso-auth-server/pom.xml @@ -20,10 +20,10 @@ - org.springframework.security.oauth.boot - spring-security-oauth2-autoconfigure - ${oauth-auto.version} + org.springframework.security.oauth + spring-security-oauth2 + ${oauth.version} - \ No newline at end of file + diff --git a/spring-security-sso/spring-security-sso-ui-2/pom.xml b/spring-security-sso/spring-security-sso-ui-2/pom.xml index 5881409c3a..e4ccb82fea 100644 --- a/spring-security-sso/spring-security-sso-ui-2/pom.xml +++ b/spring-security-sso/spring-security-sso-ui-2/pom.xml @@ -42,4 +42,4 @@ - \ No newline at end of file + diff --git a/spring-security-sso/spring-security-sso-ui/pom.xml b/spring-security-sso/spring-security-sso-ui/pom.xml index 3e85eb4737..a946db4c3b 100644 --- a/spring-security-sso/spring-security-sso-ui/pom.xml +++ b/spring-security-sso/spring-security-sso-ui/pom.xml @@ -43,4 +43,4 @@ - \ No newline at end of file + diff --git a/spring-security-stormpath/pom.xml b/spring-security-stormpath/pom.xml index 5c5783eec5..4f19921fbd 100644 --- a/spring-security-stormpath/pom.xml +++ b/spring-security-stormpath/pom.xml @@ -35,14 +35,6 @@ - - - spring-releases - Spring Releases - https://repo.spring.io/libs-release - - - spring-security-stormpath diff --git a/spring-security-thymeleaf/README.MD b/spring-security-thymeleaf/README.MD index c5deeb9946..36007bce62 100644 --- a/spring-security-thymeleaf/README.MD +++ b/spring-security-thymeleaf/README.MD @@ -4,4 +4,3 @@ Jira BAEL-1556 ### Relevant Articles: - [Spring Security with Thymeleaf](http://www.baeldung.com/spring-security-thymeleaf) -- [Working with Select and Option in Thymeleaf](http://www.baeldung.com/thymeleaf-select-option) diff --git a/spring-security-x509/keystore/Makefile b/spring-security-x509/keystore/Makefile index 63498fea76..2b5b5e8abe 100644 --- a/spring-security-x509/keystore/Makefile +++ b/spring-security-x509/keystore/Makefile @@ -20,65 +20,65 @@ all: clean create-keystore add-host create-truststore add-client create-keystore: # Generate a certificate authority (CA) - keytool -genkey -alias ca -ext BC=ca:true \ + 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) \ + 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 BC=ca:true \ + 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 \ + 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) \ + 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 -file ca.crt -rfc \ + 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 -file ca.crt \ + 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 $(CLIENTNAME) \ + keytool -genkey -alias $(CLIENTNAME) -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 $(CLIENTNAME) -ext BC=ca:true \ + keytool -certreq -alias $(CLIENTNAME) -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 \ + 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) \ + 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 $(CLIENTNAME) \ + keytool -importkeystore -srcalias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \ -srckeystore $(TRUSTSTORE) -srcstorepass $(PASSWORD) \ -destkeystore "$(CLIENTNAME).p12" -deststorepass $(PASSWORD) \ -deststoretype PKCS12 diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml index 0cee3b3129..658840e866 100644 --- a/spring-security-x509/pom.xml +++ b/spring-security-x509/pom.xml @@ -6,7 +6,8 @@ spring-security-x509 0.0.1-SNAPSHOT pom - + spring-security-x509 + parent-boot-1 com.baeldung diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index 67f2b4fbcd..5b68a8e63b 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - spring-security-x509-basic-auth 0.0.1-SNAPSHOT jar - Spring Security x.509 Basic Authentication + spring-security-x509-basic-auth Spring x.509 Authentication Demo diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml index 5cb4001a94..47ec7f971d 100644 --- a/spring-security-x509/spring-security-x509-client-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -2,11 +2,10 @@ 4.0.0 - spring-security-x509-client-auth 0.0.1-SNAPSHOT jar - Spring Security x.509 Client Authentication + spring-security-x509-client-auth Spring x.509 Client Authentication Demo diff --git a/spring-session/README.md b/spring-session/README.md index 30f70996cf..505d043e75 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -3,5 +3,5 @@ ## Spring Session Examples ### Relevant Articles: -- [Introduction to Spring Session](http://www.baeldung.com/spring-session) -- [Spring Session with JDBC](http://www.baeldung.com/spring-session-jdbc) +- [Guide to Spring Session](https://www.baeldung.com/spring-session) +- [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) diff --git a/spring-session/spring-session-redis/README.md b/spring-session/spring-session-redis/README.md index 0d802a4715..5e9304d778 100644 --- a/spring-session/spring-session-redis/README.md +++ b/spring-session/spring-session-redis/README.md @@ -3,4 +3,4 @@ ## Spring Session Examples ### Relevant Articles: -- [Introduction to Spring Session](http://www.baeldung.com/spring-session) +- [Guide to Spring Session](http://www.baeldung.com/spring-session) diff --git a/spring-session/spring-session-redis/pom.xml b/spring-session/spring-session-redis/pom.xml index 00da656226..96d90b2776 100644 --- a/spring-session/spring-session-redis/pom.xml +++ b/spring-session/spring-session-redis/pom.xml @@ -5,6 +5,7 @@ spring-session-redis 1.0.0-SNAPSHOT jar + spring-session-redis parent-boot-1 diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml index a9a8d3e96e..c693466ab0 100644 --- a/spring-sleuth/pom.xml +++ b/spring-sleuth/pom.xml @@ -6,12 +6,13 @@ spring-sleuth 1.0.0-SNAPSHOT jar + spring-sleuth - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -37,19 +38,8 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone - - false - - - - - 2.0.0.M7 + 2.0.2.RELEASE diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml index 4af318fde2..aa6eb45158 100644 --- a/spring-spel/pom.xml +++ b/spring-spel/pom.xml @@ -5,7 +5,7 @@ com.baeldung spring-spel 1.0-SNAPSHOT - Spring SpEL + spring-spel com.baeldung diff --git a/spring-state-machine/pom.xml b/spring-state-machine/pom.xml index 5d15e4dfad..b911b5b5ee 100644 --- a/spring-state-machine/pom.xml +++ b/spring-state-machine/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-state-machine - + spring-state-machine + parent-modules com.baeldung diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index 8e551d850f..e1bb98360e 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -4,6 +4,7 @@ spring-swagger-codegen 0.0.1-SNAPSHOT pom + spring-swagger-codegen com.baeldung diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index 06a92ffae7..c175ea48b3 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -189,7 +189,7 @@ 1.5.15 4.3.9.RELEASE - 2.8.9 + 2.9.7 2.9.9 2.2 1.5 diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index 4aff696828..f9410b6865 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -2,7 +2,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-swagger-codegen-app - + spring-swagger-codegen-app + com.baeldung spring-swagger-codegen diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 0926728aba..78f95fe1df 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -5,6 +5,7 @@ spring-thymeleaf 0.1-SNAPSHOT war + spring-thymeleaf com.baeldung diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java index b8132cddc8..d10caee9e7 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java @@ -21,16 +21,13 @@ import com.baeldung.thymeleaf.service.BookService; @Controller public class BookController { - private static int currentPage = 1; - private static int pageSize = 5; - @Autowired private BookService bookService; - + @RequestMapping(value = "/listBooks", method = RequestMethod.GET) public String listBooks(Model model, @RequestParam("page") Optional page, @RequestParam("size") Optional size) { - page.ifPresent(p -> currentPage = p); - size.ifPresent(s -> pageSize = s); + final int currentPage = page.orElse(1); + final int pageSize = size.orElse(5); Page bookPage = bookService.findPaginated(PageRequest.of(currentPage - 1, pageSize)); diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 7144a57ca6..e562171103 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -1,12 +1,12 @@ 4.0.0 - spring-userservice spring-userservice 0.0.1-SNAPSHOT war - + spring-userservice + com.baeldung parent-spring-4 diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index 31616cdb16..aad6da1cc3 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -41,27 +41,8 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - - - - UTF-8 - 2.0.1.RELEASE + 2.1.1.RELEASE diff --git a/spring-vertx/pom.xml b/spring-vertx/pom.xml index 790eeff128..7a0bdc81d0 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -2,17 +2,16 @@ 4.0.0 - spring-vertx jar - Spring Vertx + spring-vertx A demo project with vertx spring integration - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-webflux-amqp/pom.xml b/spring-webflux-amqp/pom.xml index 4faa165c50..0868e14717 100755 --- a/spring-webflux-amqp/pom.xml +++ b/spring-webflux-amqp/pom.xml @@ -60,23 +60,4 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/libs-snapshot - - true - - - - - - - spring-releases - Spring Releases - https://repo.spring.io/libs-release - - - diff --git a/spring-webflux-amqp/src/main/resources/application.yml b/spring-webflux-amqp/src/main/resources/application.yml index 3f527ce4c5..702aaba357 100755 --- a/spring-webflux-amqp/src/main/resources/application.yml +++ b/spring-webflux-amqp/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: rabbitmq: - host: 192.168.99.100 + host: localhost port: 5672 username: guest password: guest diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index 266c20adee..a8c891cd89 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -1,7 +1,8 @@ - 4.0.0 - + com.baeldung spring-zuul 1.0.0-SNAPSHOT @@ -9,10 +10,10 @@ pom - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -38,11 +39,22 @@ - 1.2.7.RELEASE + 2.1.0.RC3 3.5 2.6 + + + spring-milestones + Spring Milestones + http://repo.spring.io/milestone + + false + + + + \ No newline at end of file diff --git a/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java b/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java index 9f1d2e162b..77eabe771b 100644 --- a/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java +++ b/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerApplication.java @@ -2,7 +2,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class ResourceServerApplication extends SpringBootServletInitializer { diff --git a/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java b/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java index c040c8ac42..1a45d20edb 100644 --- a/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java +++ b/spring-zuul/spring-zuul-foos-resource/src/main/java/org/baeldung/config/ResourceServerWebConfig.java @@ -3,11 +3,11 @@ package org.baeldung.config; 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.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc @ComponentScan({ "org.baeldung.web.controller" }) -public class ResourceServerWebConfig extends WebMvcConfigurerAdapter { +public class ResourceServerWebConfig implements WebMvcConfigurer { } diff --git a/spring-zuul/spring-zuul-foos-resource/src/main/resources/application.properties b/spring-zuul/spring-zuul-foos-resource/src/main/resources/application.properties index 94c0984ac3..9298027030 100644 --- a/spring-zuul/spring-zuul-foos-resource/src/main/resources/application.properties +++ b/spring-zuul/spring-zuul-foos-resource/src/main/resources/application.properties @@ -1,2 +1,2 @@ -server.contextPath=/spring-zuul-foos-resource -server.port=8081 \ No newline at end of file +server.servlet.context-path=/spring-zuul-foos-resource +server.port=8081 diff --git a/spring-zuul/spring-zuul-ui/pom.xml b/spring-zuul/spring-zuul-ui/pom.xml index 6090f5f8b8..159decd331 100644 --- a/spring-zuul/spring-zuul-ui/pom.xml +++ b/spring-zuul/spring-zuul-ui/pom.xml @@ -15,7 +15,7 @@ org.springframework.cloud - spring-cloud-starter-zuul + spring-cloud-starter-netflix-zuul ${spring-cloud.version} diff --git a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java index b8eda25960..d3e13639ef 100644 --- a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,7 +2,7 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy diff --git a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiWebConfig.java b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiWebConfig.java index 0732182354..7cda1f0e95 100644 --- a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiWebConfig.java +++ b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiWebConfig.java @@ -7,11 +7,11 @@ import org.springframework.web.servlet.config.annotation.DefaultServletHandlerCo import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc -public class UiWebConfig extends WebMvcConfigurerAdapter { +public class UiWebConfig implements WebMvcConfigurer { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { @@ -25,7 +25,6 @@ public class UiWebConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/").setViewName("forward:/index"); registry.addViewController("/index"); registry.addViewController("/login"); diff --git a/sse-jaxrs/pom.xml b/sse-jaxrs/pom.xml deleted file mode 100644 index ac9bff937f..0000000000 --- a/sse-jaxrs/pom.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - 4.0.0 - - com.baeldung.sse - sse-jaxrs - 1.0-SNAPSHOT - pom - - - 1.8 - 1.8 - - - - sse-jaxrs-server - sse-jaxrs-client - - - diff --git a/sse-jaxrs/sse-jaxrs-client/pom.xml b/sse-jaxrs/sse-jaxrs-client/pom.xml deleted file mode 100644 index a9068e133f..0000000000 --- a/sse-jaxrs/sse-jaxrs-client/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - - - com.baeldung.sse - sse-jaxrs - 1.0-SNAPSHOT - - - sse-jaxrs-client - - - 3.2.0 - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - - singleEvent - - java - - - com.baeldung.sse.jaxrs.client.SseClientApp - - - - broadcast - - java - - - com.baeldung.sse.jaxrs.client.SseClientBroadcastApp - - - - - - - - - - org.apache.cxf - cxf-rt-rs-client - ${cxf-version} - - - org.apache.cxf - cxf-rt-rs-sse - ${cxf-version} - - - - diff --git a/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java deleted file mode 100644 index 5d42b3a243..0000000000 --- a/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.sse.jaxrs.client; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.sse.InboundSseEvent; -import javax.ws.rs.sse.SseEventSource; -import java.util.function.Consumer; - -public class SseClientApp { - - private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices"; - - public static void main(String... args) throws Exception { - - Client client = ClientBuilder.newClient(); - WebTarget target = client.target(url); - try (SseEventSource eventSource = SseEventSource.target(target).build()) { - - eventSource.register(onEvent, onError, onComplete); - eventSource.open(); - - //Consuming events for one hour - Thread.sleep(60 * 60 * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - client.close(); - System.out.println("End"); - } - - // A new event is received - private static Consumer onEvent = (inboundSseEvent) -> { - String data = inboundSseEvent.readData(); - System.out.println(data); - }; - - //Error - private static Consumer onError = (throwable) -> { - throwable.printStackTrace(); - }; - - //Connection close and there is nothing to receive - private static Runnable onComplete = () -> { - System.out.println("Done!"); - }; - -} diff --git a/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java deleted file mode 100644 index 9afc187a6d..0000000000 --- a/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.sse.jaxrs.client; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.sse.InboundSseEvent; -import javax.ws.rs.sse.SseEventSource; -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; - -public class SseClientBroadcastApp { - - private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe"; - - - public static void main(String... args) throws Exception { - - Client client = ClientBuilder.newClient(); - WebTarget target = client.target(subscribeUrl); - try (final SseEventSource eventSource = SseEventSource.target(target) - .reconnectingEvery(5, TimeUnit.SECONDS) - .build()) { - eventSource.register(onEvent, onError, onComplete); - eventSource.open(); - System.out.println("Wainting for incoming event ..."); - - //Consuming events for one hour - Thread.sleep(60 * 60 * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - client.close(); - System.out.println("End"); - } - - // A new event is received - private static Consumer onEvent = (inboundSseEvent) -> { - String data = inboundSseEvent.readData(); - System.out.println(data); - }; - - //Error - private static Consumer onError = (throwable) -> { - throwable.printStackTrace(); - }; - - //Connection close and there is nothing to receive - private static Runnable onComplete = () -> { - System.out.println("Done!"); - }; - -} diff --git a/sse-jaxrs/sse-jaxrs-server/pom.xml b/sse-jaxrs/sse-jaxrs-server/pom.xml deleted file mode 100644 index 1e89c70e13..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - 4.0.0 - - - com.baeldung.sse - sse-jaxrs - 1.0-SNAPSHOT - - - sse-jaxrs-server - war - - - 2.4.2 - false - 18.0.0.2 - - - - ${artifactId} - - - net.wasdev.wlp.maven.plugins - liberty-maven-plugin - ${liberty-maven-plugin.version} - - - io.openliberty - openliberty-webProfile8 - ${openliberty-version} - zip - - project - true - src/main/liberty/config/server.xml - - - - install-server - prepare-package - - install-server - create-server - install-feature - - - - install-apps - package - - install-apps - - - - - - - - - - - javax.ws.rs - javax.ws.rs-api - 2.1 - provided - - - javax.enterprise - cdi-api - 2.0 - provided - - - javax.json.bind - javax.json.bind-api - 1.0 - provided - - - - - diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java deleted file mode 100644 index 058d19f045..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.sse.jaxrs; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; - -@ApplicationPath("sse") -public class AppConfig extends Application { -} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java deleted file mode 100644 index 1f60168a1b..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.baeldung.sse.jaxrs; - -import javax.enterprise.context.ApplicationScoped; -import javax.inject.Inject; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.sse.OutboundSseEvent; -import javax.ws.rs.sse.Sse; -import javax.ws.rs.sse.SseBroadcaster; -import javax.ws.rs.sse.SseEventSink; - -@ApplicationScoped -@Path("stock") -public class SseResource { - - @Inject - private StockService stockService; - - private Sse sse; - private SseBroadcaster sseBroadcaster; - private OutboundSseEvent.Builder eventBuilder; - - @Context - public void setSse(Sse sse) { - this.sse = sse; - this.eventBuilder = sse.newEventBuilder(); - this.sseBroadcaster = sse.newBroadcaster(); - } - - @GET - @Path("prices") - @Produces("text/event-stream") - public void getStockPrices(@Context SseEventSink sseEventSink, - @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) { - - int lastEventId = 1; - if (lastReceivedId != -1) { - lastEventId = ++lastReceivedId; - } - boolean running = true; - while (running) { - Stock stock = stockService.getNextTransaction(lastEventId); - if (stock != null) { - OutboundSseEvent sseEvent = this.eventBuilder - .name("stock") - .id(String.valueOf(lastEventId)) - .mediaType(MediaType.APPLICATION_JSON_TYPE) - .data(Stock.class, stock) - .reconnectDelay(3000) - .comment("price change") - .build(); - sseEventSink.send(sseEvent); - lastEventId++; - } - //Simulate connection close - if (lastEventId % 5 == 0) { - sseEventSink.close(); - break; - } - - try { - //Wait 5 seconds - Thread.sleep(5 * 1000); - } catch (InterruptedException ex) { - // ... - } - //Simulatae a while boucle break - running = lastEventId <= 2000; - } - sseEventSink.close(); - } - - @GET - @Path("subscribe") - @Produces(MediaType.SERVER_SENT_EVENTS) - public void listen(@Context SseEventSink sseEventSink) { - sseEventSink.send(sse.newEvent("Welcome !")); - this.sseBroadcaster.register(sseEventSink); - sseEventSink.send(sse.newEvent("You are registred !")); - } - - @GET - @Path("publish") - public void broadcast() { - Runnable r = new Runnable() { - @Override - public void run() { - int lastEventId = 0; - boolean running = true; - while (running) { - lastEventId++; - Stock stock = stockService.getNextTransaction(lastEventId); - if (stock != null) { - OutboundSseEvent sseEvent = eventBuilder - .name("stock") - .id(String.valueOf(lastEventId)) - .mediaType(MediaType.APPLICATION_JSON_TYPE) - .data(Stock.class, stock) - .reconnectDelay(3000) - .comment("price change") - .build(); - sseBroadcaster.broadcast(sseEvent); - } - try { - //Wait 5 seconds - Thread.currentThread().sleep(5 * 1000); - } catch (InterruptedException ex) { - // ... - } - //Simulatae a while boucle break - running = lastEventId <= 2000; - } - } - }; - new Thread(r).start(); - } -} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java deleted file mode 100644 index a186b32771..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.sse.jaxrs; - -import java.math.BigDecimal; -import java.time.LocalDateTime; - -public class Stock { - private Integer id; - private String name; - private BigDecimal price; - LocalDateTime dateTime; - - public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) { - this.id = id; - this.name = name; - this.price = price; - this.dateTime = dateTime; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public BigDecimal getPrice() { - return price; - } - - public void setPrice(BigDecimal price) { - this.price = price; - } - - public LocalDateTime getDateTime() { - return dateTime; - } - - public void setDateTime(LocalDateTime dateTime) { - this.dateTime = dateTime; - } -} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java deleted file mode 100644 index 15818ead5d..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.sse.jaxrs; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.Initialized; -import javax.enterprise.event.Event; -import javax.enterprise.event.Observes; -import javax.inject.Inject; -import javax.inject.Named; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicInteger; - -@ApplicationScoped -@Named -public class StockService { - - private static final BigDecimal UP = BigDecimal.valueOf(1.05f); - private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f); - - List stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO"); - List stocksDB = new ArrayList<>(); - private AtomicInteger counter = new AtomicInteger(0); - - public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { - //Open price - System.out.println("@Start Init ..."); - stockNames.forEach(stockName -> { - stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now())); - }); - - Runnable runnable = new Runnable() { - @Override - public void run() { - //Simulate Change price and put every x seconds - while (true) { - int indx = new Random().nextInt(stockNames.size()); - String stockName = stockNames.get(indx); - BigDecimal price = getLastPrice(stockName); - BigDecimal newprice = changePrice(price); - Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now()); - stocksDB.add(stock); - - int r = new Random().nextInt(30); - try { - Thread.currentThread().sleep(r*1000); - } catch (InterruptedException ex) { - // ... - } - } - } - }; - new Thread(runnable).start(); - System.out.println("@End Init ..."); - } - - public Stock getNextTransaction(Integer lastEventId) { - return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null); - } - - BigDecimal generateOpenPrice() { - float min = 70; - float max = 120; - return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING); - } - - BigDecimal changePrice(BigDecimal price) { - return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING); - } - - private BigDecimal getLastPrice(String stockName) { - return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice(); - } -} diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml b/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml deleted file mode 100644 index 9bf66d7795..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - jaxrs-2.1 - cdi-2.0 - - - diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml b/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 4f0b3cdeeb..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,6 +0,0 @@ - - \ No newline at end of file diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml b/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b4b8121fdd..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - Hello Servlet - - - index.html - - - diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html deleted file mode 100644 index 9015a7a32c..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html +++ /dev/null @@ -1 +0,0 @@ -index diff --git a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html b/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html deleted file mode 100644 index 5a46e2a5d3..0000000000 --- a/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - Server-Sent Event Broadcasting - - -

Stock prices :

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

Stock prices :

-
-
    -
-
- - - \ No newline at end of file diff --git a/static-analysis/pom.xml b/static-analysis/pom.xml index 14853d81f7..94d68f895b 100644 --- a/static-analysis/pom.xml +++ b/static-analysis/pom.xml @@ -2,10 +2,10 @@ 4.0.0 - com.baeldung static-analysis 1.0-SNAPSHOT + static-analysis com.baeldung diff --git a/structurizr/pom.xml b/structurizr/pom.xml index cbbbf8d68c..b9f9b68717 100644 --- a/structurizr/pom.xml +++ b/structurizr/pom.xml @@ -2,9 +2,8 @@ 4.0.0 - - com.baeldung structurizr + structurizr com.baeldung @@ -26,32 +25,24 @@ com.structurizr structurizr-client - ${structurizr-client.version} + ${structurizr.version} - org.springframework - spring-context - ${spring.version} + com.structurizr + structurizr-analysis + ${structurizr.version} + + + com.structurizr + structurizr-plantuml + ${structurizr.version}
- - - - false - - central - bintray - http://jcenter.bintray.com - - - 1.8 1.8 - 1.0.0-RC3 - 0.6.0 - 4.3.8.RELEASE + 1.0.0-RC5 \ No newline at end of file diff --git a/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java b/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java index 6eb0c7de73..b33a1d9a77 100644 --- a/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java +++ b/structurizr/src/main/java/com/baeldung/structurizr/StructurizrSimple.java @@ -4,12 +4,10 @@ import java.io.File; import java.io.StringWriter; import com.structurizr.Workspace; -import com.structurizr.api.StructurizrClient; -import com.structurizr.api.StructurizrClientException; -import com.structurizr.componentfinder.ComponentFinder; -import com.structurizr.componentfinder.ReferencedTypesSupportingTypesStrategy; -import com.structurizr.componentfinder.SourceCodeComponentFinderStrategy; -import com.structurizr.componentfinder.SpringComponentFinderStrategy; +import com.structurizr.analysis.ComponentFinder; +import com.structurizr.analysis.ReferencedTypesSupportingTypesStrategy; +import com.structurizr.analysis.SourceCodeComponentFinderStrategy; +import com.structurizr.analysis.SpringComponentFinderStrategy; import com.structurizr.io.WorkspaceWriterException; import com.structurizr.io.plantuml.PlantUMLWriter; import com.structurizr.model.Component; @@ -112,11 +110,6 @@ public class StructurizrSimple { view.addAllContainers(); } - private static void uploadToExternal(Workspace workspace) throws StructurizrClientException { - StructurizrClient client = new StructurizrClient("e94bc0c9-76ef-41b0-8de7-82afc1010d04", "78d555dd-2a31-487c-952c-50508f1da495"); - client.putWorkspace(32961L, workspace); - } - private static void exportToPlantUml(View view) throws WorkspaceWriterException { StringWriter stringWriter = new StringWriter(); PlantUMLWriter plantUMLWriter = new PlantUMLWriter(); diff --git a/struts-2/pom.xml b/struts-2/pom.xml index fee68c8303..ac8579d9e0 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -5,7 +5,7 @@ struts-2 0.0.1-SNAPSHOT pom - Struts 2 + struts-2 com.baeldung diff --git a/testing-modules/README.md b/testing-modules/README.md index b189b9819e..d69f07215e 100644 --- a/testing-modules/README.md +++ b/testing-modules/README.md @@ -14,3 +14,4 @@ - [JSON Schema Validation with REST-assured](http://www.baeldung.com/rest-assured-json-schema) - [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks) - [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) +- [Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 8d4c89ec62..158da176c6 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -6,7 +6,8 @@ org.baeldung gatling 1.0-SNAPSHOT - + gatling + com.baeldung parent-modules diff --git a/testing-modules/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml index e0da345eb4..3dd01c29ab 100644 --- a/testing-modules/groovy-spock/pom.xml +++ b/testing-modules/groovy-spock/pom.xml @@ -6,6 +6,7 @@ groovy-spock 1.0-SNAPSHOT jar + groovy-spock com.baeldung diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java b/testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java index f9766d2bd9..2e477084aa 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java @@ -18,9 +18,9 @@ public class TestLauncher { //@formatter:off LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(selectClass("com.baeldung.EmployeesTest")) + .selectors(selectClass("com.baeldung.EmployeesUnitTest")) .configurationParameter("junit.conditions.deactivate", "com.baeldung.extensions.*") - .configurationParameter("junit.extensions.autodetection.enabled", "true") + .configurationParameter("junit.jupiter.extensions.autodetection.enabled", "true") .build(); //@formatter:on diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml new file mode 100644 index 0000000000..42614d310b --- /dev/null +++ b/testing-modules/load-testing-comparison/pom.xml @@ -0,0 +1,149 @@ + + + 4.0.0 + load-testing-comparison + load-testing-comparison + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../pom.xml + + + + 1.8 + 1.8 + UTF-8 + 2.11.12 + 2.2.5 + 3.2.2 + 2.2.1 + 5.0 + 3.11 + 2.0.5.RELEASE + + + + + io.gatling + gatling-app + ${gatling.version} + + + io.gatling + gatling-recorder + ${gatling.version} + + + io.gatling.highcharts + gatling-charts-highcharts + ${gatling.version} + + + org.scala-lang + scala-library + ${scala.version} + + + + + + + + com.fasterxml.jackson.core + jackson-databind + 2.9.4 + + + org.springframework.boot + spring-boot-starter + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-web + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring.boot.version} + test + + + com.h2database + h2 + 1.4.197 + + + org.projectlombok + lombok + 1.18.2 + compile + + + + + + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.0.5.RELEASE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/Application.java b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/Application.java new file mode 100644 index 0000000000..6647bcb640 --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.loadtesting; + +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/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/RewardsController.java b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/RewardsController.java new file mode 100644 index 0000000000..50cc6fb7ab --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/RewardsController.java @@ -0,0 +1,51 @@ +package com.baeldung.loadtesting; + +import com.baeldung.loadtesting.model.CustomerRewardsAccount; +import com.baeldung.loadtesting.model.Transaction; +import com.baeldung.loadtesting.repository.CustomerRewardsRepository; +import com.baeldung.loadtesting.repository.TransactionRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Calendar; +import java.util.List; +import java.util.Optional; + +@RestController +public class RewardsController { + + @Autowired + private CustomerRewardsRepository customerRewardsRepository; + + @Autowired + private TransactionRepository transactionRepository; + + @PostMapping(path="/transactions/add") + public @ResponseBody Transaction saveTransactions(@RequestBody Transaction trnsctn){ + trnsctn.setTransactionDate(Calendar.getInstance().getTime()); + Transaction result = transactionRepository.save(trnsctn); + return result; + } + + @GetMapping(path="/transactions/findAll/{rewardId}") + public @ResponseBody Iterable getTransactions(@PathVariable Integer rewardId){ + return transactionRepository.findByCustomerRewardsId(rewardId); + } + + @PostMapping(path="/rewards/add") + public @ResponseBody CustomerRewardsAccount addRewardsAcount(@RequestBody CustomerRewardsAccount body) { + Optional acct = customerRewardsRepository.findByCustomerId(body.getCustomerId()); + return !acct.isPresent() ? customerRewardsRepository.save(body) : acct.get(); + } + + @GetMapping(path="/rewards/find/{customerId}") + public @ResponseBody + Optional find(@PathVariable Integer customerId) { + return customerRewardsRepository.findByCustomerId(customerId); + } + + @GetMapping(path="/rewards/all") + public @ResponseBody List findAll() { + return customerRewardsRepository.findAll(); + } +} diff --git a/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/TransactionController.java b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/TransactionController.java new file mode 100644 index 0000000000..2ea2c06a41 --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/TransactionController.java @@ -0,0 +1,26 @@ +package com.baeldung.loadtesting; + +import com.baeldung.loadtesting.model.Transaction; +import com.baeldung.loadtesting.repository.TransactionRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@Deprecated +public class TransactionController { + + @Autowired + private TransactionRepository transactionRepository; + + @PostMapping(path="/addTransaction") + public @ResponseBody + String saveTransactions(@RequestBody Transaction trnsctn){ + transactionRepository.save(trnsctn); + return "Saved Transaction."; + } + + @GetMapping(path="/findAll/{rewardId}") + public @ResponseBody Iterable getTransactions(@RequestParam Integer id){ + return transactionRepository.findByCustomerRewardsId(id); + } +} diff --git a/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/model/CustomerRewardsAccount.java b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/model/CustomerRewardsAccount.java new file mode 100644 index 0000000000..2c6742fbaf --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/model/CustomerRewardsAccount.java @@ -0,0 +1,22 @@ +package com.baeldung.loadtesting.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import lombok.Data; + +@Entity +@Data +public class CustomerRewardsAccount { + + @Id + @GeneratedValue(strategy= GenerationType.AUTO) + private Integer id; + private Integer customerId; + + public Integer getCustomerId(){ + return this.customerId; + } +} diff --git a/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/model/Transaction.java b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/model/Transaction.java new file mode 100644 index 0000000000..312f52f4ab --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/model/Transaction.java @@ -0,0 +1,30 @@ +package com.baeldung.loadtesting.model; + +import lombok.Data; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.util.Date; +import java.util.Calendar; + +@Entity +@Data +public class Transaction { + + @Id + @GeneratedValue(strategy= GenerationType.AUTO) + private Integer id; + private Integer customerRewardsId; + private Integer customerId; + private Date transactionDate; + + public Transaction(){ + transactionDate = Calendar.getInstance().getTime(); + } + + public void setTransactionDate(Date transactionDate){ + this.transactionDate = transactionDate; + } +} diff --git a/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/repository/CustomerRewardsRepository.java b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/repository/CustomerRewardsRepository.java new file mode 100644 index 0000000000..f945359eb8 --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/repository/CustomerRewardsRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.loadtesting.repository; + +import com.baeldung.loadtesting.model.CustomerRewardsAccount; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface CustomerRewardsRepository extends JpaRepository { + + Optional findByCustomerId(Integer customerId); +} diff --git a/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/repository/TransactionRepository.java b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/repository/TransactionRepository.java new file mode 100644 index 0000000000..af0b343c10 --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/java/com/baeldung/loadtesting/repository/TransactionRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.loadtesting.repository; + +import com.baeldung.loadtesting.model.Transaction; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface TransactionRepository extends JpaRepository { + + List findByCustomerRewardsId(Integer rewardsId); +} diff --git a/testing-modules/load-testing-comparison/src/main/resources/scripts/Gatling/GatlingScenario.scala b/testing-modules/load-testing-comparison/src/main/resources/scripts/Gatling/GatlingScenario.scala new file mode 100644 index 0000000000..f9b3837759 --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/resources/scripts/Gatling/GatlingScenario.scala @@ -0,0 +1,52 @@ +package com.baeldung + +import scala.util._ +import io.gatling.core.Predef._ +import io.gatling.http.Predef._ +import scala.concurrent.duration._ + +class RewardsScenario extends Simulation { + + def randCustId() = Random.nextInt(99) + + val httpProtocol = http.baseUrl("http://localhost:8080") + .acceptHeader("text/html,application/json;q=0.9,*/*;q=0.8") + .doNotTrackHeader("1") + .acceptLanguageHeader("en-US,en;q=0.5") + .acceptEncodingHeader("gzip, deflate") + .userAgentHeader("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0") + + val scn = scenario("RewardsScenario") + .repeat(10){ + exec(http("transactions_add") + .post("/transactions/add/") + .body(StringBody("""{ "customerRewardsId":null,"customerId":""""+ randCustId() + """","transactionDate":null }""")).asJson + .check(jsonPath("$.id").saveAs("txnId")) + .check(jsonPath("$.transactionDate").saveAs("txtDate")) + .check(jsonPath("$.customerId").saveAs("custId"))) + .pause(1) + + .exec(http("get_reward") + .get("/rewards/find/${custId}") + .check(jsonPath("$.id").saveAs("rwdId"))) + .pause(1) + + .doIf("${rwdId.isUndefined()}"){ + exec(http("rewards_add") + .post("/rewards/add") + .body(StringBody("""{ "customerId": "${custId}" }""")).asJson + .check(jsonPath("$.id").saveAs("rwdId"))) + } + + .exec(http("transactions_add") + .post("/transactions/add/") + .body(StringBody("""{ "customerRewardsId":"${rwdId}","customerId":"${custId}","transactionDate":"${txtDate}" }""")).asJson) + .pause(1) + + .exec(http("get_reward") + .get("/transactions/findAll/${rwdId}")) + } + setUp( + scn.inject(atOnceUsers(100)) + ).protocols(httpProtocol) +} \ No newline at end of file diff --git a/testing-modules/load-testing-comparison/src/main/resources/scripts/JMeter/Test Plan.jmx b/testing-modules/load-testing-comparison/src/main/resources/scripts/JMeter/Test Plan.jmx new file mode 100644 index 0000000000..da32a13a22 --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/resources/scripts/JMeter/Test Plan.jmx @@ -0,0 +1,293 @@ + + + + + + false + true + false + + + + + + + + continue + + false + 10 + + 100 + 0 + false + + + + + + true + 1 + + + + + + Content-Type + application/json + + + + + + true + + + + false + {"customerRewardsId":null,"customerId":${random},"transactionDate":null} + = + + + + localhost + 8080 + http + + /transactions/add + POST + true + false + true + false + + + + + + + txnId + $.id + 1 + all + foo + + + + txnDate + $.transactionDate + 1 + Never + + + + custId + $.customerId + 1 + all + bob + + + + + + + + localhost + 8080 + + + /rewards/find/${custId} + GET + true + false + true + false + + + + + + + rwdId + $.id + 1 + 0 + all + + + + + ${rwdId} == 0 + true + + + + true + + + + false + {"customerId":${custId}} + = + + + + localhost + 8080 + + + /rewards/add + POST + true + false + true + false + + + + + + + rwdId + $.id + 1 + bar + all + + + + + + true + + + + false + {"id":${txnId},"customerRewardsId":${rwdId},"customerId":${custId},"transactionDate":"${txnDate}"} + = + + + + localhost + 8080 + + + /transactions/add + POST + true + false + true + false + + + + + + + + + + localhost + 8080 + + + /transactions/findAll/${rwdId} + GET + true + false + true + false + + + + + + + + 10000 + 1 + + false + 67 + random + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + + + + + + + diff --git a/testing-modules/load-testing-comparison/src/main/resources/scripts/The Grinder/grinder.properties b/testing-modules/load-testing-comparison/src/main/resources/scripts/The Grinder/grinder.properties new file mode 100644 index 0000000000..68adf90856 --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/resources/scripts/The Grinder/grinder.properties @@ -0,0 +1,5 @@ +grinder.script = grinder.py +grinder.threads = 100 +grinder.processes = 1 +grinder.runs = 10 +grinder.logDirectory = /logs diff --git a/testing-modules/load-testing-comparison/src/main/resources/scripts/The Grinder/grinder.py b/testing-modules/load-testing-comparison/src/main/resources/scripts/The Grinder/grinder.py new file mode 100644 index 0000000000..025f90d38b --- /dev/null +++ b/testing-modules/load-testing-comparison/src/main/resources/scripts/The Grinder/grinder.py @@ -0,0 +1,40 @@ +import java.util.Random +from net.grinder.script import Test +from net.grinder.script.Grinder import grinder +from net.grinder.plugin.http import HTTPRequest, HTTPPluginControl, HTTPUtilities +from HTTPClient import NVPair + +def parseJsonString(json, element): + for x in json.split(","): + pc = x.replace('"','').split(":") + if pc[0].replace("{","") == element: + ele = pc[1].replace("}","") + return ele + else: + return "" + +test1 = Test(1, "Request resource") +request1 = HTTPRequest() +headers = \ +( NVPair('Content-Type', 'application/json'), ) +request1.setHeaders(headers) +utilities = HTTPPluginControl.getHTTPUtilities() +test1.record(request1) +random=java.util.Random() + +class TestRunner: + def __call__(self): + customerId = str(random.nextInt()); + + result = request1.POST("http://localhost:8080/transactions/add", "{"'"customerRewardsId"'":null,"'"customerId"'":"+ customerId + ","'"transactionDate"'":null}") + txnId = parseJsonString(result.getText(), "id") + + result = request1.GET("http://localhost:8080/rewards/find/"+ customerId) + rwdId = parseJsonString(result.getText(), "id") + + if rwdId == "": + result = request1.POST("http://localhost:8080/rewards/add", "{"'"customerId"'":"+ customerId + "}") + rwdId = parseJsonString(result.getText(), "id") + + result = request1.POST("http://localhost:8080/transactions/add", "{"'"id"'":" + txnId + ","'"customerRewardsId"'":" + rwdId + ","'"customerId"'":"+ customerId + ","'"transactionDate"'":null}") + result = request1.GET("http://localhost:8080/transactions/findAll/" + rwdId) \ No newline at end of file diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index cab4d7977b..5f60566566 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -5,7 +5,7 @@ mockito-2 0.0.1-SNAPSHOT jar - mockito-2-with-java8 + mockito-2 com.baeldung diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index e1b9c27523..158a1918e7 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -14,8 +14,7 @@ - [Mocking Void Methods with Mockito](http://www.baeldung.com/mockito-void-methods) - [Mocking of Private Methods Using PowerMock](http://www.baeldung.com/powermock-private-method) - [Mock Final Classes and Methods with Mockito](http://www.baeldung.com/mockito-final) -- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) -- [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers) - [Hamcrest Custom Matchers](http://www.baeldung.com/hamcrest-custom-matchers) - [Hamcrest Common Core Matchers](http://www.baeldung.com/hamcrest-core-matchers) - [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks) +- [Using Hamcrest Number Matchers](https://www.baeldung.com/hamcrest-number-matchers) diff --git a/testing-modules/mockserver/pom.xml b/testing-modules/mockserver/pom.xml index c2fa2870e2..1db409bd7c 100644 --- a/testing-modules/mockserver/pom.xml +++ b/testing-modules/mockserver/pom.xml @@ -5,7 +5,8 @@ com.baeldung mockserver 1.0.0-SNAPSHOT - + mockserver + com.baeldung parent-modules diff --git a/testing-modules/parallel-tests-junit/pom.xml b/testing-modules/parallel-tests-junit/pom.xml index 3fd4e695e5..ecca8b3930 100644 --- a/testing-modules/parallel-tests-junit/pom.xml +++ b/testing-modules/parallel-tests-junit/pom.xml @@ -5,6 +5,8 @@ parallel-tests-junit 0.0.1-SNAPSHOT pom + parallel-tests-junit + math-test-functions string-test-functions diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index ed7e5e3577..687a9a2fe4 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -171,7 +171,7 @@ - 2.8.5 + 2.9.7 1.8 19.0 diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 9bfd715682..2fa303a98e 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -151,7 +151,7 @@ - 2.8.5 + 2.9.7 19.0 diff --git a/testing-modules/selenium-junit-testng/pom.xml b/testing-modules/selenium-junit-testng/pom.xml index e22f7421cf..ae15fc97c0 100644 --- a/testing-modules/selenium-junit-testng/pom.xml +++ b/testing-modules/selenium-junit-testng/pom.xml @@ -4,7 +4,8 @@ com.baeldung selenium-junit-testng 0.0.1-SNAPSHOT - + selenium-junit-testng + com.baeldung parent-modules diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index e22c3e84e7..02ab7b24bd 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -2,3 +2,4 @@ - [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) - [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) +- [Guide to ReflectionTestUtils for Unit Testing](https://www.baeldung.com/spring-reflection-test-utils) diff --git a/twilio/pom.xml b/twilio/pom.xml index 610cc04b60..81fbf8ab20 100644 --- a/twilio/pom.xml +++ b/twilio/pom.xml @@ -4,7 +4,8 @@ 4.0.0 twilio 1.0-SNAPSHOT - + twilio + parent-modules com.baeldung diff --git a/vaadin/src/main/resources/application.properties b/vaadin/src/main/resources/application.properties new file mode 100644 index 0000000000..1cb7086b82 --- /dev/null +++ b/vaadin/src/main/resources/application.properties @@ -0,0 +1,2 @@ +#Vaadin supports spring-boot 2.1 properly from V8 onwards (according to this comment https://github.com/vaadin/spring/issues/331#issuecomment-435128475) +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/vavr/README.md b/vavr/README.md index b7ba72229b..0857765ec6 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -9,6 +9,5 @@ - [Guide to Collections API in Vavr](http://www.baeldung.com/vavr-collections) - [Collection Factory Methods for Vavr](http://www.baeldung.com/vavr-collection-factory-methods) - [Introduction to Future in Vavr](http://www.baeldung.com/vavr-future) -- [Introduction to VRaptor in Java](http://www.baeldung.com/vraptor) - [Introduction to Vavr’s Either](http://www.baeldung.com/vavr-either) - [Interoperability Between Java and Vavr](http://www.baeldung.com/java-vavr) diff --git a/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/application/Application.java b/vavr/src/main/java/com/baeldung/vavrvalidation/application/Application.java similarity index 95% rename from vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/application/Application.java rename to vavr/src/main/java/com/baeldung/vavrvalidation/application/Application.java index 8acc4522af..a23ed185c8 100644 --- a/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/application/Application.java +++ b/vavr/src/main/java/com/baeldung/vavrvalidation/application/Application.java @@ -8,10 +8,10 @@ import io.vavr.control.Validation; public class Application { public static void main(String[] args) { - + UserValidator userValidator = new UserValidator(); Validation, User> validation = userValidator.validateUser("John", "john@domain.com"); - + // process validation results here - } + } } diff --git a/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/model/User.java b/vavr/src/main/java/com/baeldung/vavrvalidation/model/User.java similarity index 100% rename from vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/model/User.java rename to vavr/src/main/java/com/baeldung/vavrvalidation/model/User.java diff --git a/vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/validator/UserValidator.java b/vavr/src/main/java/com/baeldung/vavrvalidation/validator/UserValidator.java similarity index 100% rename from vavr/vavr-validation/src/main/java/com/baeldung/vavrvalidation/validator/UserValidator.java rename to vavr/src/main/java/com/baeldung/vavrvalidation/validator/UserValidator.java diff --git a/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorTest.java b/vavr/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorUnitTest.java similarity index 95% rename from vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorTest.java rename to vavr/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorUnitTest.java index cb9557fa53..8ac6100b27 100644 --- a/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorTest.java +++ b/vavr/src/test/java/com/baeldung/vavrvalidation/validator/UserValidatorUnitTest.java @@ -7,7 +7,7 @@ import com.baeldung.vavrvalidation.validator.UserValidator; import io.vavr.control.Validation.Invalid; import io.vavr.control.Validation.Valid; -public class UserValidatorTest { +public class UserValidatorUnitTest { @Test public void givenValidUserParams_whenValidated_thenInstanceOfValid() { diff --git a/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/ValidationTest.java b/vavr/src/test/java/com/baeldung/vavrvalidation/validator/ValidationUnitTest.java similarity index 98% rename from vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/ValidationTest.java rename to vavr/src/test/java/com/baeldung/vavrvalidation/validator/ValidationUnitTest.java index c89b43b5e3..7b8c551aeb 100644 --- a/vavr/vavr-validation/src/test/java/com/baeldung/vavrvalidation/validator/ValidationTest.java +++ b/vavr/src/test/java/com/baeldung/vavrvalidation/validator/ValidationUnitTest.java @@ -11,7 +11,7 @@ import io.vavr.control.Either.Right; import io.vavr.control.Validation.Invalid; import io.vavr.control.Validation.Valid; -public class ValidationTest { +public class ValidationUnitTest { private static UserValidator userValidator; diff --git a/vertx-and-rxjava/pom.xml b/vertx-and-rxjava/pom.xml index cbc94dd8f1..389eaf687b 100644 --- a/vertx-and-rxjava/pom.xml +++ b/vertx-and-rxjava/pom.xml @@ -3,7 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 vertx-and-rxjava - + vertx-and-rxjava + com.baeldung parent-modules diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 748721b83c..b0e1c7e8d9 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -1,11 +1,10 @@ 4.0.0 - com.baeldung jackson-annotations 1.0.0-SNAPSHOT - jacksonannotation + jackson-annotations com.baeldung @@ -139,7 +138,7 @@ - 2.8.5 + 2.9.7 2.9.6 diff --git a/vraptor/pom.xml b/vraptor/pom.xml index ae43d8e083..97005bd158 100644 --- a/vraptor/pom.xml +++ b/vraptor/pom.xml @@ -1,11 +1,11 @@ 4.0.0 - com.baeldung vraptor 1.0.0 war + vraptor A demo project to start using VRaptor 4 diff --git a/xml/pom.xml b/xml/pom.xml index 5490f3a89f..dfdec4da16 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -24,7 +24,6 @@ ${jaxen.version} - org.jdom jdom2 @@ -166,7 +165,7 @@ template-binding.xml - src/main/resources + src/main/resources *-binding.xml @@ -174,14 +173,14 @@ - process-classes + process-classes process-classes bind - - process-test-classes + + process-test-classes process-test-classes test-bind @@ -230,34 +229,6 @@ - - - jibx.sf.net - JiBX repository - http://jibx.sf.net/maven2 - - never - - - false - - - - - - - jibx.sf.net - JiBX repository - http://jibx.sf.net/maven2 - - never - - - false - - - - 1.6.1 1.1.6 diff --git a/xmlunit-2/pom.xml b/xmlunit-2/pom.xml index 806ebb6c0e..faefeca7a1 100644 --- a/xmlunit-2/pom.xml +++ b/xmlunit-2/pom.xml @@ -4,6 +4,7 @@ com.baeldung xmlunit-2 1.0 + xmlunit-2 com.baeldung