diff --git a/README.md b/README.md index f3fe5e3bf0..378d77196a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Java and Spring Tutorials ================ This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem. -A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt. +A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security. In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`. diff --git a/akka-http/README.md b/akka-http/README.md new file mode 100644 index 0000000000..3831b5079f --- /dev/null +++ b/akka-http/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to Akka HTTP](https://www.baeldung.com/akka-http) 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-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md index a04874c4d2..6f18396005 100644 --- a/algorithms-miscellaneous-1/README.md +++ b/algorithms-miscellaneous-1/README.md @@ -10,4 +10,8 @@ - [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) +- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters) +- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique) diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java new file mode 100644 index 0000000000..7fedd78ffb --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java @@ -0,0 +1,123 @@ +package com.baeldung.algorithms.permutation; + +import java.util.Arrays; +import java.util.Collections; + +public class Permutation { + + public static void printAllRecursive(T[] elements, char delimiter) { + printAllRecursive(elements.length, elements, delimiter); + } + + public static void printAllRecursive(int n, T[] elements, char delimiter) { + + if(n == 1) { + printArray(elements, delimiter); + } else { + for(int i = 0; i < n-1; i++) { + printAllRecursive(n - 1, elements, delimiter); + if(n % 2 == 0) { + swap(elements, i, n-1); + } else { + swap(elements, 0, n-1); + } + } + printAllRecursive(n - 1, elements, delimiter); + } + } + + public static void printAllIterative(int n, T[] elements, char delimiter) { + + int[] indexes = new int[n]; + for (int i = 0; i < n; i++) { + indexes[i] = 0; + } + + printArray(elements, delimiter); + + int i = 0; + while (i < n) { + if (indexes[i] < i) { + swap(elements, i % 2 == 0 ? 0: indexes[i], i); + printArray(elements, delimiter); + indexes[i]++; + i = 0; + } + else { + indexes[i] = 0; + i++; + } + } + } + + public static > void printAllOrdered(T[] elements, char delimiter) { + + Arrays.sort(elements); + boolean hasNext = true; + + while(hasNext) { + printArray(elements, delimiter); + int k = 0, l = 0; + hasNext = false; + for (int i = elements.length - 1; i > 0; i--) { + if (elements[i].compareTo(elements[i - 1]) > 0) { + k = i - 1; + hasNext = true; + break; + } + } + + for (int i = elements.length - 1; i > k; i--) { + if (elements[i].compareTo(elements[k]) > 0) { + l = i; + break; + } + } + + swap(elements, k, l); + Collections.reverse(Arrays.asList(elements).subList(k + 1, elements.length)); + } + } + + public static void printRandom(T[] elements, char delimiter) { + + Collections.shuffle(Arrays.asList(elements)); + printArray(elements, delimiter); + } + + private static void swap(T[] elements, int a, int b) { + + T tmp = elements[a]; + elements[a] = elements[b]; + elements[b] = tmp; + } + + private static void printArray(T[] elements, char delimiter) { + + String delimiterSpace = delimiter + " "; + for(int i = 0; i < elements.length; i++) { + System.out.print(elements[i] + delimiterSpace); + } + System.out.print('\n'); + } + + public static void main(String[] argv) { + + Integer[] elements = {1,2,3,4}; + + System.out.println("Rec:"); + printAllRecursive(elements, ';'); + + System.out.println("Iter:"); + printAllIterative(elements.length, elements, ';'); + + System.out.println("Orderes:"); + printAllOrdered(elements, ';'); + + System.out.println("Random:"); + printRandom(elements, ';'); + + System.out.println("Random:"); + printRandom(elements, ';'); + } +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java new file mode 100644 index 0000000000..a7031f4fba --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms.twopointertechnique; + +public class LinkedListFindMiddle { + + public T findMiddle(MyNode head) { + MyNode slowPointer = head; + MyNode fastPointer = head; + + while (fastPointer.next != null && fastPointer.next.next != null) { + fastPointer = fastPointer.next.next; + slowPointer = slowPointer.next; + } + return slowPointer.data; + } + +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java new file mode 100644 index 0000000000..7d93f03ef9 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.twopointertechnique; + +public class MyNode { + MyNode next; + E data; + + public MyNode(E value) { + data = value; + next = null; + } + + public MyNode(E value, MyNode n) { + data = value; + next = n; + } + + public void setNext(MyNode n) { + next = n; + } +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java new file mode 100644 index 0000000000..b4e3698c01 --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java @@ -0,0 +1,22 @@ +package com.baeldung.algorithms.twopointertechnique; + +public class RotateArray { + + public void rotate(int[] input, int step) { + step %= input.length; + reverse(input, 0, input.length - 1); + reverse(input, 0, step - 1); + reverse(input, step, input.length - 1); + } + + private void reverse(int[] input, int start, int end) { + while (start < end) { + int temp = input[start]; + input[start] = input[end]; + input[end] = temp; + start++; + end--; + } + } + +} diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java new file mode 100644 index 0000000000..14eceaa1bd --- /dev/null +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.twopointertechnique; + +public class TwoSum { + + public boolean twoSum(int[] input, int targetValue) { + + int pointerOne = 0; + int pointerTwo = input.length - 1; + + while (pointerOne < pointerTwo) { + int sum = input[pointerOne] + input[pointerTwo]; + + if (sum == targetValue) { + return true; + } else if (sum < targetValue) { + pointerOne++; + } else { + pointerTwo--; + } + } + + return false; + } + + public boolean twoSumSlow(int[] input, int targetValue) { + + for (int i = 0; i < input.length; i++) { + for (int j = 1; j < input.length; j++) { + if (input[i] + input[j] == targetValue) { + return true; + } + } + } + + return false; + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java new file mode 100644 index 0000000000..422a53fa3e --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.algorithms.twopointertechnique; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class LinkedListFindMiddleUnitTest { + + LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle(); + + @Test + public void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() { + + MyNode head = createNodesList(8); + + assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("4"); + + head = createNodesList(9); + + assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("5"); + } + + private static MyNode createNodesList(int n) { + + MyNode head = new MyNode("1"); + MyNode current = head; + + for (int i = 2; i <= n; i++) { + MyNode newNode = new MyNode(String.valueOf(i)); + current.setNext(newNode); + current = newNode; + } + + return head; + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java new file mode 100644 index 0000000000..da227ae751 --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.twopointertechnique; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class RotateArrayUnitTest { + + private RotateArray rotateArray = new RotateArray(); + + private int[] inputArray; + + private int step; + + @Test + public void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() { + + inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 }; + step = 4; + + rotateArray.rotate(inputArray, step); + + assertThat(inputArray).containsExactly(new int[] { 4, 5, 6, 7, 1, 2, 3 }); + } + +} diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java new file mode 100644 index 0000000000..aa76f8e1cf --- /dev/null +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.algorithms.twopointertechnique; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class TwoSumUnitTest { + + private TwoSum twoSum = new TwoSum(); + + private int[] sortedArray; + + private int targetValue; + + @Test + public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() { + + sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + + targetValue = 12; + + assertTrue(twoSum.twoSumSlow(sortedArray, targetValue)); + } + + @Test + public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() { + + sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + + targetValue = 20; + + assertFalse(twoSum.twoSumSlow(sortedArray, targetValue)); + } + + @Test + public void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() { + + sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + + targetValue = 12; + + assertTrue(twoSum.twoSum(sortedArray, targetValue)); + } + + @Test + public void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() { + + sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; + + targetValue = 20; + + assertFalse(twoSum.twoSum(sortedArray, targetValue)); + } + +} diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml index bcca38b199..e6be32277d 100644 --- a/apache-curator/pom.xml +++ b/apache-curator/pom.xml @@ -59,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-spark/pom.xml b/apache-spark/pom.xml index 290b63a14d..b05b97198d 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -15,16 +15,76 @@ - org.apache.spark - spark-core_2.10 + spark-core_2.11 ${org.apache.spark.spark-core.version} + provided + + org.apache.spark + spark-sql_2.11 + ${org.apache.spark.spark-sql.version} + provided + + + org.apache.spark + spark-streaming_2.11 + ${org.apache.spark.spark-streaming.version} + provided + + + org.apache.spark + spark-streaming-kafka-0-10_2.11 + ${org.apache.spark.spark-streaming-kafka.version} + + + com.datastax.spark + spark-cassandra-connector_2.11 + ${com.datastax.spark.spark-cassandra-connector.version} + + + com.datastax.spark + spark-cassandra-connector-java_2.11 + ${com.datastax.spark.spark-cassandra-connector-java.version} + - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.8 + 1.8 + + + + maven-assembly-plugin + + + package + + single + + + + + + jar-with-dependencies + + + + + - 2.2.0 + 2.3.0 + 2.3.0 + 2.3.0 + 2.3.0 + 2.3.0 + 1.5.2 diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/Word.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/Word.java new file mode 100644 index 0000000000..b0caa468b1 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/Word.java @@ -0,0 +1,25 @@ +package com.baeldung.data.pipeline; + +import java.io.Serializable; + +public class Word implements Serializable { + private static final long serialVersionUID = 1L; + private String word; + private int count; + Word(String word, int count) { + this.word = word; + this.count = count; + } + public String getWord() { + return word; + } + public void setWord(String word) { + this.word = word; + } + public int getCount() { + return count; + } + public void setCount(int count) { + this.count = count; + } +} \ No newline at end of file diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java new file mode 100644 index 0000000000..db2a73b411 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java @@ -0,0 +1,80 @@ +package com.baeldung.data.pipeline; + +import static com.datastax.spark.connector.japi.CassandraJavaUtil.javaFunctions; +import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.apache.spark.SparkConf; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.streaming.Durations; +import org.apache.spark.streaming.api.java.JavaDStream; +import org.apache.spark.streaming.api.java.JavaInputDStream; +import org.apache.spark.streaming.api.java.JavaPairDStream; +import org.apache.spark.streaming.api.java.JavaStreamingContext; +import org.apache.spark.streaming.kafka010.ConsumerStrategies; +import org.apache.spark.streaming.kafka010.KafkaUtils; +import org.apache.spark.streaming.kafka010.LocationStrategies; + +import scala.Tuple2; + +public class WordCountingApp { + + public static void main(String[] args) throws InterruptedException { + Logger.getLogger("org") + .setLevel(Level.OFF); + Logger.getLogger("akka") + .setLevel(Level.OFF); + + Map kafkaParams = new HashMap<>(); + kafkaParams.put("bootstrap.servers", "localhost:9092"); + kafkaParams.put("key.deserializer", StringDeserializer.class); + kafkaParams.put("value.deserializer", StringDeserializer.class); + kafkaParams.put("group.id", "use_a_separate_group_id_for_each_stream"); + kafkaParams.put("auto.offset.reset", "latest"); + kafkaParams.put("enable.auto.commit", false); + + Collection topics = Arrays.asList("messages"); + + SparkConf sparkConf = new SparkConf(); + sparkConf.setMaster("local[2]"); + sparkConf.setAppName("WordCountingApp"); + sparkConf.set("spark.cassandra.connection.host", "127.0.0.1"); + + JavaStreamingContext streamingContext = new JavaStreamingContext(sparkConf, Durations.seconds(1)); + + JavaInputDStream> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies. Subscribe(topics, kafkaParams)); + + JavaPairDStream results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value())); + + JavaDStream lines = results.map(tuple2 -> tuple2._2()); + + JavaDStream words = lines.flatMap(x -> Arrays.asList(x.split("\\s+")) + .iterator()); + + JavaPairDStream wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1)) + .reduceByKey((i1, i2) -> i1 + i2); + + wordCounts.foreachRDD(javaRdd -> { + Map wordCountMap = javaRdd.collectAsMap(); + for (String key : wordCountMap.keySet()) { + List wordList = Arrays.asList(new Word(key, wordCountMap.get(key))); + JavaRDD rdd = streamingContext.sparkContext() + .parallelize(wordList); + javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class)) + .saveToCassandra(); + } + }); + + streamingContext.start(); + streamingContext.awaitTermination(); + } +} \ No newline at end of file diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java new file mode 100644 index 0000000000..efbe5f3851 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java @@ -0,0 +1,97 @@ +package com.baeldung.data.pipeline; + +import static com.datastax.spark.connector.japi.CassandraJavaUtil.javaFunctions; +import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.apache.spark.SparkConf; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.api.java.function.Function2; +import org.apache.spark.streaming.Durations; +import org.apache.spark.streaming.StateSpec; +import org.apache.spark.streaming.api.java.JavaDStream; +import org.apache.spark.streaming.api.java.JavaInputDStream; +import org.apache.spark.streaming.api.java.JavaMapWithStateDStream; +import org.apache.spark.streaming.api.java.JavaPairDStream; +import org.apache.spark.streaming.api.java.JavaStreamingContext; +import org.apache.spark.streaming.kafka010.ConsumerStrategies; +import org.apache.spark.streaming.kafka010.KafkaUtils; +import org.apache.spark.streaming.kafka010.LocationStrategies; + +import scala.Tuple2; + +public class WordCountingAppWithCheckpoint { + + public static JavaSparkContext sparkContext; + + public static void main(String[] args) throws InterruptedException { + + Logger.getLogger("org") + .setLevel(Level.OFF); + Logger.getLogger("akka") + .setLevel(Level.OFF); + + Map kafkaParams = new HashMap<>(); + kafkaParams.put("bootstrap.servers", "localhost:9092"); + kafkaParams.put("key.deserializer", StringDeserializer.class); + kafkaParams.put("value.deserializer", StringDeserializer.class); + kafkaParams.put("group.id", "use_a_separate_group_id_for_each_stream"); + kafkaParams.put("auto.offset.reset", "latest"); + kafkaParams.put("enable.auto.commit", false); + + Collection topics = Arrays.asList("messages"); + + SparkConf sparkConf = new SparkConf(); + sparkConf.setMaster("local[2]"); + sparkConf.setAppName("WordCountingAppWithCheckpoint"); + sparkConf.set("spark.cassandra.connection.host", "127.0.0.1"); + + JavaStreamingContext streamingContext = new JavaStreamingContext(sparkConf, Durations.seconds(1)); + + sparkContext = streamingContext.sparkContext(); + + streamingContext.checkpoint("./.checkpoint"); + + JavaInputDStream> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies. Subscribe(topics, kafkaParams)); + + JavaPairDStream results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value())); + + JavaDStream lines = results.map(tuple2 -> tuple2._2()); + + JavaDStream words = lines.flatMap(x -> Arrays.asList(x.split("\\s+")) + .iterator()); + + JavaPairDStream wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1)) + .reduceByKey((Function2) (i1, i2) -> i1 + i2); + + JavaMapWithStateDStream> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> { + int sum = one.orElse(0) + (state.exists() ? state.get() : 0); + Tuple2 output = new Tuple2<>(word, sum); + state.update(sum); + return output; + })); + + cumulativeWordCounts.foreachRDD(javaRdd -> { + List> wordCountList = javaRdd.collect(); + for (Tuple2 tuple : wordCountList) { + List wordList = Arrays.asList(new Word(tuple._1, tuple._2)); + JavaRDD rdd = sparkContext.parallelize(wordList); + javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class)) + .saveToCassandra(); + } + }); + + streamingContext.start(); + streamingContext.awaitTermination(); + } +} \ No newline at end of file diff --git a/axon/pom.xml b/axon/pom.xml index c643ea9e57..598dc820e5 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -4,29 +4,61 @@ 4.0.0 axon axon - + Basic Axon Framework with Spring Boot configuration tutorial + - parent-modules com.baeldung - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + org.axonframework + axon-spring-boot-starter + ${axon.version} + + + org.axonframework + axon-server-connector + + + + org.axonframework axon-test ${axon.version} test + - org.axonframework - axon-core - ${axon.version} + org.springframework.boot + spring-boot-autoconfigure + 2.1.1.RELEASE + compile + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime - 3.0.2 + 4.0.3 \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/MessagesRunner.java b/axon/src/main/java/com/baeldung/axon/MessagesRunner.java deleted file mode 100644 index 77b50d09bd..0000000000 --- a/axon/src/main/java/com/baeldung/axon/MessagesRunner.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.axon; - -import com.baeldung.axon.aggregates.MessagesAggregate; -import com.baeldung.axon.commands.CreateMessageCommand; -import com.baeldung.axon.commands.MarkReadMessageCommand; -import com.baeldung.axon.eventhandlers.MessagesEventHandler; -import org.axonframework.commandhandling.AggregateAnnotationCommandHandler; -import org.axonframework.commandhandling.CommandBus; -import org.axonframework.commandhandling.SimpleCommandBus; -import org.axonframework.commandhandling.gateway.CommandGateway; -import org.axonframework.commandhandling.gateway.DefaultCommandGateway; -import org.axonframework.eventhandling.AnnotationEventListenerAdapter; -import org.axonframework.eventsourcing.EventSourcingRepository; -import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore; -import org.axonframework.eventsourcing.eventstore.EventStore; -import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine; - -import java.util.UUID; - -public class MessagesRunner { - - public static void main(String[] args) { - CommandBus commandBus = new SimpleCommandBus(); - - CommandGateway commandGateway = new DefaultCommandGateway(commandBus); - - EventStore eventStore = new EmbeddedEventStore(new InMemoryEventStorageEngine()); - - EventSourcingRepository repository = - new EventSourcingRepository<>(MessagesAggregate.class, eventStore); - - - AggregateAnnotationCommandHandler messagesAggregateAggregateAnnotationCommandHandler = - new AggregateAnnotationCommandHandler(MessagesAggregate.class, repository); - messagesAggregateAggregateAnnotationCommandHandler.subscribe(commandBus); - - final AnnotationEventListenerAdapter annotationEventListenerAdapter = - new AnnotationEventListenerAdapter(new MessagesEventHandler()); - eventStore.subscribe(eventMessages -> eventMessages.forEach(e -> { - try { - annotationEventListenerAdapter.handle(e); - } catch (Exception e1) { - throw new RuntimeException(e1); - - } - } - - )); - - final String itemId = UUID.randomUUID().toString(); - commandGateway.send(new CreateMessageCommand(itemId, "Hello, how is your day? :-)")); - commandGateway.send(new MarkReadMessageCommand(itemId)); - } -} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/OrderApplication.java b/axon/src/main/java/com/baeldung/axon/OrderApplication.java new file mode 100644 index 0000000000..8f507e141c --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/OrderApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.axon; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class OrderApplication { + + public static void main(String[] args) { + SpringApplication.run(OrderApplication.class, args); + } + +} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java b/axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java deleted file mode 100644 index e762604b74..0000000000 --- a/axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.axon.aggregates; - -import com.baeldung.axon.commands.CreateMessageCommand; -import com.baeldung.axon.commands.MarkReadMessageCommand; -import com.baeldung.axon.events.MessageCreatedEvent; -import com.baeldung.axon.events.MessageReadEvent; -import org.axonframework.commandhandling.CommandHandler; -import org.axonframework.commandhandling.model.AggregateIdentifier; -import org.axonframework.eventhandling.EventHandler; - -import static org.axonframework.commandhandling.model.AggregateLifecycle.apply; - - -public class MessagesAggregate { - - @AggregateIdentifier - private String id; - - public MessagesAggregate() { - } - - @CommandHandler - public MessagesAggregate(CreateMessageCommand command) { - apply(new MessageCreatedEvent(command.getId(), command.getText())); - } - - @EventHandler - public void on(MessageCreatedEvent event) { - this.id = event.getId(); - } - - @CommandHandler - public void markRead(MarkReadMessageCommand command) { - apply(new MessageReadEvent(id)); - } -} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java new file mode 100644 index 0000000000..b37b2fdd66 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java @@ -0,0 +1,58 @@ +package com.baeldung.axon.commandmodel; + +import static org.axonframework.modelling.command.AggregateLifecycle.apply; + +import org.axonframework.commandhandling.CommandHandler; +import org.axonframework.eventsourcing.EventSourcingHandler; +import org.axonframework.modelling.command.AggregateIdentifier; +import org.axonframework.spring.stereotype.Aggregate; + +import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand; +import com.baeldung.axon.coreapi.commands.PlaceOrderCommand; +import com.baeldung.axon.coreapi.commands.ShipOrderCommand; +import com.baeldung.axon.coreapi.events.OrderConfirmedEvent; +import com.baeldung.axon.coreapi.events.OrderPlacedEvent; +import com.baeldung.axon.coreapi.events.OrderShippedEvent; + +@Aggregate +public class OrderAggregate { + + @AggregateIdentifier + private String orderId; + private boolean orderConfirmed; + + @CommandHandler + public OrderAggregate(PlaceOrderCommand command) { + apply(new OrderPlacedEvent(command.getOrderId(), command.getProduct())); + } + + @CommandHandler + public void handle(ConfirmOrderCommand command) { + apply(new OrderConfirmedEvent(orderId)); + } + + @CommandHandler + public void handle(ShipOrderCommand command) { + if (!orderConfirmed) { + throw new IllegalStateException("Cannot ship an order which has not been confirmed yet."); + } + + apply(new OrderShippedEvent(orderId)); + } + + @EventSourcingHandler + public void on(OrderPlacedEvent event) { + this.orderId = event.getOrderId(); + orderConfirmed = false; + } + + @EventSourcingHandler + public void on(OrderConfirmedEvent event) { + orderConfirmed = true; + } + + protected OrderAggregate() { + // Required by Axon to build a default Aggregate prior to Event Sourcing + } + +} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/commands/CreateMessageCommand.java b/axon/src/main/java/com/baeldung/axon/commands/CreateMessageCommand.java deleted file mode 100644 index d0651bf12e..0000000000 --- a/axon/src/main/java/com/baeldung/axon/commands/CreateMessageCommand.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.axon.commands; - - -import org.axonframework.commandhandling.TargetAggregateIdentifier; - -public class CreateMessageCommand { - - @TargetAggregateIdentifier - private final String id; - private final String text; - - public CreateMessageCommand(String id, String text) { - this.id = id; - this.text = text; - } - - public String getId() { - return id; - } - - public String getText() { - return text; - } -} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/commands/MarkReadMessageCommand.java b/axon/src/main/java/com/baeldung/axon/commands/MarkReadMessageCommand.java deleted file mode 100644 index e66582d9ec..0000000000 --- a/axon/src/main/java/com/baeldung/axon/commands/MarkReadMessageCommand.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.axon.commands; - - -import org.axonframework.commandhandling.TargetAggregateIdentifier; - -public class MarkReadMessageCommand { - - @TargetAggregateIdentifier - private final String id; - - public MarkReadMessageCommand(String id) { - this.id = id; - } - - public String getId() { - return id; - } -} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java new file mode 100644 index 0000000000..244b69f3b7 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java @@ -0,0 +1,43 @@ +package com.baeldung.axon.coreapi.commands; + +import org.axonframework.modelling.command.TargetAggregateIdentifier; + +import java.util.Objects; + +public class ConfirmOrderCommand { + + @TargetAggregateIdentifier + private final String orderId; + + public ConfirmOrderCommand(String orderId) { + this.orderId = orderId; + } + + public String getOrderId() { + return orderId; + } + + @Override + public int hashCode() { + return Objects.hash(orderId); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final ConfirmOrderCommand other = (ConfirmOrderCommand) obj; + return Objects.equals(this.orderId, other.orderId); + } + + @Override + public String toString() { + return "ConfirmOrderCommand{" + + "orderId='" + orderId + '\'' + + '}'; + } +} diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/PlaceOrderCommand.java b/axon/src/main/java/com/baeldung/axon/coreapi/commands/PlaceOrderCommand.java new file mode 100644 index 0000000000..c70d503050 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/commands/PlaceOrderCommand.java @@ -0,0 +1,51 @@ +package com.baeldung.axon.coreapi.commands; + +import java.util.Objects; + +import org.axonframework.modelling.command.TargetAggregateIdentifier; + +public class PlaceOrderCommand { + + @TargetAggregateIdentifier + private final String orderId; + private final String product; + + public PlaceOrderCommand(String orderId, String product) { + this.orderId = orderId; + this.product = product; + } + + public String getOrderId() { + return orderId; + } + + public String getProduct() { + return product; + } + + @Override + public int hashCode() { + return Objects.hash(orderId, product); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final PlaceOrderCommand other = (PlaceOrderCommand) obj; + return Objects.equals(this.orderId, other.orderId) + && Objects.equals(this.product, other.product); + } + + @Override + public String toString() { + return "PlaceOrderCommand{" + + "orderId='" + orderId + '\'' + + ", product='" + product + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java new file mode 100644 index 0000000000..7312bc1fdb --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java @@ -0,0 +1,43 @@ +package com.baeldung.axon.coreapi.commands; + +import java.util.Objects; + +import org.axonframework.modelling.command.TargetAggregateIdentifier; + +public class ShipOrderCommand { + + @TargetAggregateIdentifier + private final String orderId; + + public ShipOrderCommand(String orderId) { + this.orderId = orderId; + } + + public String getOrderId() { + return orderId; + } + + @Override + public int hashCode() { + return Objects.hash(orderId); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final ShipOrderCommand other = (ShipOrderCommand) obj; + return Objects.equals(this.orderId, other.orderId); + } + + @Override + public String toString() { + return "ShipOrderCommand{" + + "orderId='" + orderId + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java new file mode 100644 index 0000000000..d2b7d58435 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java @@ -0,0 +1,40 @@ +package com.baeldung.axon.coreapi.events; + +import java.util.Objects; + +public class OrderConfirmedEvent { + + private final String orderId; + + public OrderConfirmedEvent(String orderId) { + this.orderId = orderId; + } + + public String getOrderId() { + return orderId; + } + + @Override + public int hashCode() { + return Objects.hash(orderId); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final OrderConfirmedEvent other = (OrderConfirmedEvent) obj; + return Objects.equals(this.orderId, other.orderId); + } + + @Override + public String toString() { + return "OrderConfirmedEvent{" + + "orderId='" + orderId + '\'' + + '}'; + } +} diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderPlacedEvent.java b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderPlacedEvent.java new file mode 100644 index 0000000000..06de4c5f9f --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderPlacedEvent.java @@ -0,0 +1,48 @@ +package com.baeldung.axon.coreapi.events; + +import java.util.Objects; + +public class OrderPlacedEvent { + + private final String orderId; + private final String product; + + public OrderPlacedEvent(String orderId, String product) { + this.orderId = orderId; + this.product = product; + } + + public String getOrderId() { + return orderId; + } + + public String getProduct() { + return product; + } + + @Override + public int hashCode() { + return Objects.hash(orderId, product); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final OrderPlacedEvent other = (OrderPlacedEvent) obj; + return Objects.equals(this.orderId, other.orderId) + && Objects.equals(this.product, other.product); + } + + @Override + public String toString() { + return "OrderPlacedEvent{" + + "orderId='" + orderId + '\'' + + ", product='" + product + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java new file mode 100644 index 0000000000..76aa684629 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java @@ -0,0 +1,40 @@ +package com.baeldung.axon.coreapi.events; + +import java.util.Objects; + +public class OrderShippedEvent { + + private final String orderId; + + public OrderShippedEvent(String orderId) { + this.orderId = orderId; + } + + public String getOrderId() { + return orderId; + } + + @Override + public int hashCode() { + return Objects.hash(orderId); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final OrderShippedEvent other = (OrderShippedEvent) obj; + return Objects.equals(this.orderId, other.orderId); + } + + @Override + public String toString() { + return "OrderShippedEvent{" + + "orderId='" + orderId + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java b/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java new file mode 100644 index 0000000000..9d6ca2cfb2 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java @@ -0,0 +1,5 @@ +package com.baeldung.axon.coreapi.queries; + +public class FindAllOrderedProductsQuery { + +} diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java new file mode 100644 index 0000000000..d215c5fc32 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java @@ -0,0 +1,7 @@ +package com.baeldung.axon.coreapi.queries; + +public enum OrderStatus { + + PLACED, CONFIRMED, SHIPPED + +} diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderedProduct.java b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderedProduct.java new file mode 100644 index 0000000000..d847bb2a98 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderedProduct.java @@ -0,0 +1,64 @@ +package com.baeldung.axon.coreapi.queries; + +import java.util.Objects; + +public class OrderedProduct { + + private final String orderId; + private final String product; + private OrderStatus orderStatus; + + public OrderedProduct(String orderId, String product) { + this.orderId = orderId; + this.product = product; + orderStatus = OrderStatus.PLACED; + } + + public String getOrderId() { + return orderId; + } + + public String getProduct() { + return product; + } + + public OrderStatus getOrderStatus() { + return orderStatus; + } + + public void setOrderConfirmed() { + this.orderStatus = OrderStatus.CONFIRMED; + } + + public void setOrderShipped() { + this.orderStatus = OrderStatus.SHIPPED; + } + + @Override + public int hashCode() { + return Objects.hash(orderId, product, orderStatus); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final OrderedProduct other = (OrderedProduct) obj; + return Objects.equals(this.orderId, other.orderId) + && Objects.equals(this.product, other.product) + && Objects.equals(this.orderStatus, other.orderStatus); + } + + @Override + public String toString() { + return "OrderedProduct{" + + "orderId='" + orderId + '\'' + + ", product='" + product + '\'' + + ", orderStatus=" + orderStatus + + '}'; + } +} diff --git a/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java b/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java deleted file mode 100644 index 3e51e19c4e..0000000000 --- a/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.axon.eventhandlers; - -import com.baeldung.axon.events.MessageReadEvent; -import com.baeldung.axon.events.MessageCreatedEvent; -import org.axonframework.eventhandling.EventHandler; - - -public class MessagesEventHandler { - - @EventHandler - public void handle(MessageCreatedEvent event) { - System.out.println("Message received: " + event.getText() + " (" + event.getId() + ")"); - } - - @EventHandler - public void handle(MessageReadEvent event) { - System.out.println("Message read: " + event.getId()); - } -} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/events/MessageCreatedEvent.java b/axon/src/main/java/com/baeldung/axon/events/MessageCreatedEvent.java deleted file mode 100644 index 3c9aac5ed8..0000000000 --- a/axon/src/main/java/com/baeldung/axon/events/MessageCreatedEvent.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.axon.events; - -public class MessageCreatedEvent { - - private final String id; - private final String text; - - public MessageCreatedEvent(String id, String text) { - this.id = id; - this.text = text; - } - - public String getId() { - return id; - } - - public String getText() { - return text; - } -} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/events/MessageReadEvent.java b/axon/src/main/java/com/baeldung/axon/events/MessageReadEvent.java deleted file mode 100644 index 57bfc8e19e..0000000000 --- a/axon/src/main/java/com/baeldung/axon/events/MessageReadEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.axon.events; - -public class MessageReadEvent { - - private final String id; - - public MessageReadEvent(String id) { - this.id = id; - } - - public String getId() { - return id; - } -} \ No newline at end of file diff --git a/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java b/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java new file mode 100644 index 0000000000..a9f34cc691 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java @@ -0,0 +1,52 @@ +package com.baeldung.axon.gui; + +import java.util.List; +import java.util.UUID; + +import org.axonframework.commandhandling.gateway.CommandGateway; +import org.axonframework.messaging.responsetypes.ResponseTypes; +import org.axonframework.queryhandling.QueryGateway; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand; +import com.baeldung.axon.coreapi.commands.PlaceOrderCommand; +import com.baeldung.axon.coreapi.commands.ShipOrderCommand; +import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery; +import com.baeldung.axon.coreapi.queries.OrderedProduct; + +@RestController +public class OrderRestEndpoint { + + private final CommandGateway commandGateway; + private final QueryGateway queryGateway; + + public OrderRestEndpoint(CommandGateway commandGateway, QueryGateway queryGateway) { + this.commandGateway = commandGateway; + this.queryGateway = queryGateway; + } + + @PostMapping("/ship-order") + public void shipOrder() { + String orderId = UUID.randomUUID().toString(); + commandGateway.send(new PlaceOrderCommand(orderId, "Deluxe Chair")); + commandGateway.send(new ConfirmOrderCommand(orderId)); + commandGateway.send(new ShipOrderCommand(orderId)); + } + + @PostMapping("/ship-unconfirmed-order") + public void shipUnconfirmedOrder() { + String orderId = UUID.randomUUID().toString(); + commandGateway.send(new PlaceOrderCommand(orderId, "Deluxe Chair")); + // This throws an exception, as an Order cannot be shipped if it has not been confirmed yet. + commandGateway.send(new ShipOrderCommand(orderId)); + } + + @GetMapping("/all-orders") + public List findAllOrderedProducts() { + return queryGateway.query(new FindAllOrderedProductsQuery(), ResponseTypes.multipleInstancesOf(OrderedProduct.class)) + .join(); + } + +} diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java new file mode 100644 index 0000000000..d4cf3d999b --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java @@ -0,0 +1,50 @@ +package com.baeldung.axon.querymodel; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.axonframework.eventhandling.EventHandler; +import org.axonframework.queryhandling.QueryHandler; +import org.springframework.stereotype.Service; + +import com.baeldung.axon.coreapi.events.OrderConfirmedEvent; +import com.baeldung.axon.coreapi.events.OrderPlacedEvent; +import com.baeldung.axon.coreapi.events.OrderShippedEvent; +import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery; +import com.baeldung.axon.coreapi.queries.OrderedProduct; + +@Service +public class OrderedProductsEventHandler { + + private final Map orderedProducts = new HashMap<>(); + + @EventHandler + public void on(OrderPlacedEvent event) { + String orderId = event.getOrderId(); + orderedProducts.put(orderId, new OrderedProduct(orderId, event.getProduct())); + } + + @EventHandler + public void on(OrderConfirmedEvent event) { + orderedProducts.computeIfPresent(event.getOrderId(), (orderId, orderedProduct) -> { + orderedProduct.setOrderConfirmed(); + return orderedProduct; + }); + } + + @EventHandler + public void on(OrderShippedEvent event) { + orderedProducts.computeIfPresent(event.getOrderId(), (orderId, orderedProduct) -> { + orderedProduct.setOrderShipped(); + return orderedProduct; + }); + } + + @QueryHandler + public List handle(FindAllOrderedProductsQuery query) { + return new ArrayList<>(orderedProducts.values()); + } + +} \ No newline at end of file diff --git a/axon/src/main/resources/order-api.http b/axon/src/main/resources/order-api.http new file mode 100644 index 0000000000..a3c69c72bc --- /dev/null +++ b/axon/src/main/resources/order-api.http @@ -0,0 +1,11 @@ +POST http://localhost:8080/ship-order + +### + +POST http://localhost:8080/ship-unconfirmed-order + +### + +GET http://localhost:8080/all-orders + +### diff --git a/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.java b/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.java deleted file mode 100644 index ad099d2c2b..0000000000 --- a/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.axon; - -import com.baeldung.axon.aggregates.MessagesAggregate; -import com.baeldung.axon.commands.CreateMessageCommand; -import com.baeldung.axon.commands.MarkReadMessageCommand; -import com.baeldung.axon.events.MessageCreatedEvent; -import com.baeldung.axon.events.MessageReadEvent; -import org.axonframework.test.aggregate.AggregateTestFixture; -import org.axonframework.test.aggregate.FixtureConfiguration; -import org.junit.Before; -import org.junit.Test; - -import java.util.UUID; - -public class MessagesAggregateIntegrationTest { - - private FixtureConfiguration fixture; - - @Before - public void setUp() throws Exception { - fixture = new AggregateTestFixture(MessagesAggregate.class); - - } - - @Test - public void giveAggregateRoot_whenCreateMessageCommand_thenShouldProduceMessageCreatedEvent() throws Exception { - String eventText = "Hello, how is your day?"; - String id = UUID.randomUUID().toString(); - fixture.given() - .when(new CreateMessageCommand(id, eventText)) - .expectEvents(new MessageCreatedEvent(id, eventText)); - } - - @Test - public void givenMessageCreatedEvent_whenReadMessageCommand_thenShouldProduceMessageReadEvent() throws Exception { - String id = UUID.randomUUID().toString(); - - fixture.given(new MessageCreatedEvent(id, "Hello :-)")) - .when(new MarkReadMessageCommand(id)) - .expectEvents(new MessageReadEvent(id)); - } -} \ No newline at end of file diff --git a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java new file mode 100644 index 0000000000..9beedbaa19 --- /dev/null +++ b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.axon.commandmodel; + +import java.util.UUID; + +import org.axonframework.test.aggregate.AggregateTestFixture; +import org.axonframework.test.aggregate.FixtureConfiguration; +import org.junit.*; + +import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand; +import com.baeldung.axon.coreapi.commands.PlaceOrderCommand; +import com.baeldung.axon.coreapi.commands.ShipOrderCommand; +import com.baeldung.axon.coreapi.events.OrderConfirmedEvent; +import com.baeldung.axon.coreapi.events.OrderPlacedEvent; +import com.baeldung.axon.coreapi.events.OrderShippedEvent; + +public class OrderAggregateUnitTest { + + private FixtureConfiguration fixture; + + @Before + public void setUp() { + fixture = new AggregateTestFixture<>(OrderAggregate.class); + } + + @Test + public void giveNoPriorActivity_whenPlaceOrderCommand_thenShouldPublishOrderPlacedEvent() { + String orderId = UUID.randomUUID().toString(); + String product = "Deluxe Chair"; + fixture.givenNoPriorActivity() + .when(new PlaceOrderCommand(orderId, product)) + .expectEvents(new OrderPlacedEvent(orderId, product)); + } + + @Test + public void givenOrderPlacedEvent_whenConfirmOrderCommand_thenShouldPublishOrderConfirmedEvent() { + String orderId = UUID.randomUUID().toString(); + String product = "Deluxe Chair"; + fixture.given(new OrderPlacedEvent(orderId, product)) + .when(new ConfirmOrderCommand(orderId)) + .expectEvents(new OrderConfirmedEvent(orderId)); + } + + @Test + public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() { + String orderId = UUID.randomUUID().toString(); + String product = "Deluxe Chair"; + fixture.given(new OrderPlacedEvent(orderId, product)) + .when(new ShipOrderCommand(orderId)) + .expectException(IllegalStateException.class); + } + + @Test + public void givenOrderPlacedEventAndOrderConfirmedEvent_whenShipOrderCommand_thenShouldPublishOrderShippedEvent() { + String orderId = UUID.randomUUID().toString(); + String product = "Deluxe Chair"; + fixture.given(new OrderPlacedEvent(orderId, product), new OrderConfirmedEvent(orderId)) + .when(new ShipOrderCommand(orderId)) + .expectEvents(new OrderShippedEvent(orderId)); + } + +} \ No newline at end of file diff --git a/core-java-11/README.md b/core-java-11/README.md index 181ada3f45..c8039f4bc5 100644 --- a/core-java-11/README.md +++ b/core-java-11/README.md @@ -2,4 +2,4 @@ - [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) - +- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api) 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/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 6786b29120..892dc71f76 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) @@ -34,3 +33,8 @@ - [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) +- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) 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/polymorphysim/Circle.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java deleted file mode 100644 index bf0e613567..0000000000 --- a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java +++ /dev/null @@ -1,21 +0,0 @@ -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); - } - -} 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 deleted file mode 100644 index 2cf4fafee1..0000000000 --- a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.interfaces.polymorphysim; - -import java.util.ArrayList; - -public class DisplayShape { - - private ArrayList 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/MainPolymorphic.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java deleted file mode 100644 index cc43c1300b..0000000000 --- a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java +++ /dev/null @@ -1,15 +0,0 @@ -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/Square.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java deleted file mode 100644 index 9c440150b5..0000000000 --- a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java +++ /dev/null @@ -1,20 +0,0 @@ -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; - } -} 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 deleted file mode 100644 index 7ded5e6621..0000000000 --- a/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java +++ /dev/null @@ -1,26 +0,0 @@ -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/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/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java b/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java new file mode 100644 index 0000000000..7dbcd2a3a3 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java @@ -0,0 +1,44 @@ +package com.baeldung.java9.set; + +import com.google.common.collect.ImmutableSet; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public class UnmodifiableSet { + + public static void main(String[] args) { + + Set set = new HashSet<>(); + set.add("Canada"); + set.add("USA"); + + coreJDK(set); + guavaOf(); + copyOf(set); + java9Of(); + } + + private static void java9Of() { + Set immutable = Set.of("Canada", "USA"); + System.out.println(immutable); + } + + private static void guavaOf() { + Set immutable = ImmutableSet.of("Canada", "USA"); + System.out.println(immutable); + } + + private static void copyOf(Set set) { + Set immutable = ImmutableSet.copyOf(set); + set.add("Costa Rica"); + System.out.println(immutable); + } + + private static void coreJDK(Set set) { + Set unmodifiableSet = Collections.unmodifiableSet(set); + set.add("Costa Rica"); + System.out.println(unmodifiableSet); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java index 9e7e8e6e4b..28e71affcc 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java @@ -1,5 +1,7 @@ package com.baeldung.java9; +import java.util.Collections; +import java.util.HashSet; import java.util.Set; import org.junit.Test; @@ -23,4 +25,14 @@ public class SetExamplesUnitTest { Set intSet = Set.of(intArray); assertEquals(intSet.size(), intArray.length); } + + @Test(expected = UnsupportedOperationException.class) + public void testUnmodifiableSet() { + Set set = new HashSet<>(); + set.add("Canada"); + set.add("USA"); + + Set unmodifiableSet = Collections.unmodifiableSet(set); + unmodifiableSet.add("Costa Rica"); + } } diff --git a/core-java-arrays/README.md b/core-java-arrays/README.md index 56110585ac..400dd7793c 100644 --- a/core-java-arrays/README.md +++ b/core-java-arrays/README.md @@ -13,3 +13,4 @@ - [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) +- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md new file mode 100644 index 0000000000..a35e714006 --- /dev/null +++ b/core-java-collections-list/README.md @@ -0,0 +1,28 @@ +========= + +## 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) +- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) 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/src/main/java/com/baeldung/java/list/WaysToIterate.java b/core-java-collections-list/src/main/java/com/baeldung/java/list/WaysToIterate.java similarity index 100% rename from core-java-collections/src/main/java/com/baeldung/java/list/WaysToIterate.java rename to core-java-collections-list/src/main/java/com/baeldung/java/list/WaysToIterate.java 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/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java b/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java similarity index 51% rename from core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java rename to core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java index 72045d6761..e11f8e8ba0 100644 --- a/core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java @@ -6,30 +6,29 @@ public class ArrayListOfArrayList { public static void main(String args[]) { - int vertex = 5; - ArrayList> graph = new ArrayList<>(vertex); + int vertexCount = 3; + ArrayList> graph = new ArrayList<>(vertexCount); //Initializing each element of ArrayList with ArrayList - for(int i=0; i< vertex; i++) { + 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(0).add(5); - graph.get(1).add(0); graph.get(1).add(2); + graph.get(2).add(0); + graph.get(1).add(0); graph.get(2).add(1); - graph.get(2).add(3); - graph.get(3).add(2); - graph.get(3).add(4); - graph.get(4).add(3); - graph.get(4).add(5); + graph.get(0).add(2); - //Printing all the edges - for(int i=0; i > > space = new ArrayList<>(x_axis_length); //Initializing each element of ArrayList with ArrayList< ArrayList > - for(int i=0; i< x_axis_length; i++) { + 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++) { + 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("Red"); - space.get(0).get(0).add("Red"); + 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("Blue"); - space.get(0).get(1).add("Blue"); + 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("Green"); - space.get(1).get(0).add("Green"); + 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("Yellow"); - space.get(1).get(1).add("Yellow"); + 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 + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-collections/src/test/java/com/baeldung/array/converter/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/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java b/core-java-collections-list/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java rename to core-java-collections-list/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java 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 4c0b24cd5d..be83621429 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,15 +25,9 @@ - [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) -- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list) +- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator) +- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) 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/main/java/com/baeldung/java/list/VectorExample.java b/core-java-collections/src/main/java/com/baeldung/java/list/VectorExample.java new file mode 100644 index 0000000000..7debc07911 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/list/VectorExample.java @@ -0,0 +1,27 @@ +package com.baeldung.java.list; + +import java.util.Enumeration; +import java.util.Iterator; +import java.util.Vector; + +public class VectorExample { + + public static void main(String[] args) { + + Vector vector = new Vector<>(); + vector.add("baeldung"); + vector.add("Vector"); + vector.add("example"); + + Enumeration e = vector.elements(); + while(e.hasMoreElements()){ + System.out.println(e.nextElement()); + } + + Iterator iterator = vector.iterator(); + while (iterator.hasNext()) { + System.out.println(iterator.next()); + } + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java index dddd85007d..331ae8d908 100644 --- a/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java +++ b/core-java-collections/src/main/java/com/baeldung/performance/ArrayListBenchmark.java @@ -9,7 +9,7 @@ import java.util.*; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(TimeUnit.MICROSECONDS) +@OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 10) public class ArrayListBenchmark { @@ -17,6 +17,7 @@ public class ArrayListBenchmark { public static class MyState { List employeeList = new ArrayList<>(); + Vector employeeVector = new Vector<>(); //LinkedList employeeList = new LinkedList<>(); long iterations = 100000; @@ -29,9 +30,11 @@ public class ArrayListBenchmark { public void setUp() { for (long i = 0; i < iterations; i++) { employeeList.add(new Employee(i, "John")); + employeeVector.add(new Employee(i, "John")); } employeeList.add(employee); + employeeVector.add(employee); employeeIndex = employeeList.indexOf(employee); } } @@ -46,6 +49,11 @@ public class ArrayListBenchmark { return state.employeeList.contains(state.employee); } + @Benchmark + public boolean testContainsVector(ArrayListBenchmark.MyState state) { + return state.employeeVector.contains(state.employee); + } + @Benchmark public int testIndexOf(ArrayListBenchmark.MyState state) { return state.employeeList.indexOf(state.employee); @@ -56,19 +64,24 @@ public class ArrayListBenchmark { return state.employeeList.get(state.employeeIndex); } + @Benchmark + public Employee testVectorGet(ArrayListBenchmark.MyState state) { + return state.employeeVector.get(state.employeeIndex); + } + @Benchmark public boolean testRemove(ArrayListBenchmark.MyState state) { return state.employeeList.remove(state.employee); } -// @Benchmark -// public void testAdd(ArrayListBenchmark.MyState state) { -// state.employeeList.add(new Employee(state.iterations + 1, "John")); -// } + @Benchmark + public void testAdd(ArrayListBenchmark.MyState state) { + state.employeeList.add(new Employee(state.iterations + 1, "John")); + } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() - .include(ArrayListBenchmark.class.getSimpleName()).threads(1) + .include(ArrayListBenchmark.class.getSimpleName()).threads(3) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); diff --git a/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java b/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java new file mode 100644 index 0000000000..6b088a5079 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/queueInterface/CustomBaeldungQueue.java @@ -0,0 +1,48 @@ +package com.baeldung.queueinterface; + +import java.util.AbstractQueue; +import java.util.Iterator; +import java.util.LinkedList; + +public class CustomBaeldungQueue extends AbstractQueue { + + private LinkedList elements; + + public CustomBaeldungQueue() { + this.elements = new LinkedList(); + } + + @Override + public Iterator iterator() { + return elements.iterator(); + } + + @Override + public int size() { + return elements.size(); + } + + @Override + public boolean offer(T t) { + if(t == null) return false; + elements.add(t); + return true; + } + + @Override + public T poll() { + + Iterator iter = elements.iterator(); + T t = iter.next(); + if(t != null){ + iter.remove(); + return t; + } + return null; + } + + @Override + public T peek() { + return elements.getFirst(); + } +} 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/com/baeldung/queueInterface/PriorityQueueUnitTest.java b/core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java new file mode 100644 index 0000000000..c5b564b55b --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.queueinterface; + +import org.junit.Before; +import org.junit.Test; + +import java.util.PriorityQueue; + +import static org.junit.Assert.assertEquals; + +public class PriorityQueueUnitTest { + + + + @Test + public void givenIntegerQueue_whenIntegersOutOfOrder_checkRetrievalOrderIsNatural() { + + PriorityQueue integerQueue = new PriorityQueue<>(); + + integerQueue.add(9); + integerQueue.add(2); + integerQueue.add(4); + + int first = integerQueue.poll(); + int second = integerQueue.poll(); + int third = integerQueue.poll(); + + assertEquals(2, first); + assertEquals(4, second); + assertEquals(9, third); + + + } + + @Test + public void givenStringQueue_whenStringsAddedOutOfNaturalOrder_checkRetrievalOrderNatural() { + + PriorityQueue stringQueue = new PriorityQueue<>(); + + stringQueue.add("banana"); + stringQueue.add("apple"); + stringQueue.add("cherry"); + + String first = stringQueue.poll(); + String second = stringQueue.poll(); + String third = stringQueue.poll(); + + assertEquals("apple", first); + assertEquals("banana", second); + assertEquals("cherry", third); + + + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java b/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java new file mode 100644 index 0000000000..6dec768542 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.queueinterface; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class CustomBaeldungQueueUnitTest { + + private CustomBaeldungQueue customQueue; + + @Before + public void setUp() throws Exception { + customQueue = new CustomBaeldungQueue<>(); + } + + @Test + public void givenQueueWithTwoElements_whenElementsRetrieved_checkRetrievalCorrect() { + + customQueue.add(7); + customQueue.add(5); + + int first = customQueue.poll(); + int second = customQueue.poll(); + + assertEquals(7, first); + assertEquals(5, second); + + } +} 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 56% rename from core-java-concurrency/README.md rename to core-java-concurrency-advanced/README.md index 2db7b91cde..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) -- [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/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java 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/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java 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/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java 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 100% 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 diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java b/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java rename to core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java 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/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java 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/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java b/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java similarity index 100% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java rename to core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java 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/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java similarity index 100% rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java rename to core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java 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-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java new file mode 100644 index 0000000000..0c5caba8a0 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java @@ -0,0 +1,86 @@ +package com.baeldung.concurrent.threadsafety.application; + +import com.baeldung.concurrent.threadsafety.callables.AtomicCounterCallable; +import com.baeldung.concurrent.threadsafety.mathutils.MathUtils; +import com.baeldung.concurrent.threadsafety.callables.CounterCallable; +import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; +import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable; +import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable; +import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.AtomicCounter; +import com.baeldung.concurrent.threadsafety.services.Counter; +import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.MessageService; +import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; +import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class Application { + + public static void main(String[] args) throws InterruptedException, ExecutionException { + + new Thread(() -> { + System.out.println(MathUtils.factorial(10)); + }).start(); + new Thread(() -> { + System.out.println(MathUtils.factorial(5)); + }).start(); + + ExecutorService executorService = Executors.newFixedThreadPool(10); + MessageService messageService = new MessageService("Welcome to Baeldung!"); + Future future1 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + Future future2 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + System.out.println(future1.get()); + System.out.println(future2.get()); + + Counter counter = new Counter(); + Future future3 = (Future) executorService.submit(new CounterCallable(counter)); + Future future4 = (Future) executorService.submit(new CounterCallable(counter)); + System.out.println(future3.get()); + System.out.println(future4.get()); + + ExtrinsicLockCounter extrinsicLockCounter = new ExtrinsicLockCounter(); + Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); + Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); + System.out.println(future5.get()); + System.out.println(future6.get()); + + ReentrantLockCounter reentrantLockCounter = new ReentrantLockCounter(); + Future future7 = (Future) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter)); + Future future8 = (Future) executorService.submit(new ReentrantLockCounterCallable(reentrantLockCounter)); + System.out.println(future7.get()); + System.out.println(future8.get()); + + ReentrantReadWriteLockCounter reentrantReadWriteLockCounter = new ReentrantReadWriteLockCounter(); + Future future9 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter)); + Future future10 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(reentrantReadWriteLockCounter)); + System.out.println(future9.get()); + System.out.println(future10.get()); + + AtomicCounter atomicCounter = new AtomicCounter(); + Future future11 = (Future) executorService.submit(new AtomicCounterCallable(atomicCounter)); + Future future12 = (Future) executorService.submit(new AtomicCounterCallable(atomicCounter)); + System.out.println(future11.get()); + System.out.println(future12.get()); + + Collection syncCollection = Collections.synchronizedCollection(new ArrayList<>()); + Thread thread11 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6))); + Thread thread12 = new Thread(() -> syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6))); + thread11.start(); + thread12.start(); + + Map concurrentMap = new ConcurrentHashMap<>(); + concurrentMap.put("1", "one"); + concurrentMap.put("2", "two"); + concurrentMap.put("3", "three"); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/AtomicCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/AtomicCounterCallable.java new file mode 100644 index 0000000000..d711299b5c --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/AtomicCounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.AtomicCounter; +import java.util.concurrent.Callable; + +public class AtomicCounterCallable implements Callable { + + private final AtomicCounter counter; + + public AtomicCounterCallable(AtomicCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/CounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/CounterCallable.java new file mode 100644 index 0000000000..cdcd84a17b --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/CounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.Counter; +import java.util.concurrent.Callable; + +public class CounterCallable implements Callable { + + private final Counter counter; + + public CounterCallable(Counter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java new file mode 100644 index 0000000000..29533e7630 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import java.util.concurrent.Callable; + +public class ExtrinsicLockCounterCallable implements Callable { + + private final ExtrinsicLockCounter counter; + + public ExtrinsicLockCounterCallable(ExtrinsicLockCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/MessageServiceCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/MessageServiceCallable.java new file mode 100644 index 0000000000..84e8c7bb51 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/MessageServiceCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.MessageService; +import java.util.concurrent.Callable; + +public class MessageServiceCallable implements Callable { + + private final MessageService messageService; + + public MessageServiceCallable(MessageService messageService) { + this.messageService = messageService; + + } + + @Override + public String call() { + return messageService.getMesssage(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentranReadWriteLockCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentranReadWriteLockCounterCallable.java new file mode 100644 index 0000000000..e806460d50 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentranReadWriteLockCounterCallable.java @@ -0,0 +1,20 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; +import java.util.concurrent.Callable; + +public class ReentranReadWriteLockCounterCallable implements Callable { + + private final ReentrantReadWriteLockCounter counter; + + public ReentranReadWriteLockCounterCallable(ReentrantReadWriteLockCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } + +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentrantLockCounterCallable.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentrantLockCounterCallable.java new file mode 100644 index 0000000000..3511a98c60 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ReentrantLockCounterCallable.java @@ -0,0 +1,19 @@ +package com.baeldung.concurrent.threadsafety.callables; + +import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; +import java.util.concurrent.Callable; + +public class ReentrantLockCounterCallable implements Callable { + + private final ReentrantLockCounter counter; + + public ReentrantLockCounterCallable(ReentrantLockCounter counter) { + this.counter = counter; + } + + @Override + public Integer call() throws Exception { + counter.incrementCounter(); + return counter.getCounter(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/mathutils/MathUtils.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/mathutils/MathUtils.java new file mode 100644 index 0000000000..f560cd4281 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/mathutils/MathUtils.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.threadsafety.mathutils; + +import java.math.BigInteger; + +public class MathUtils { + + public static BigInteger factorial(int number) { + BigInteger f = new BigInteger("1"); + for (int i = 2; i <= number; i++) { + f = f.multiply(BigInteger.valueOf(i)); + } + return f; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/AtomicCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/AtomicCounter.java new file mode 100644 index 0000000000..32a373495c --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/AtomicCounter.java @@ -0,0 +1,18 @@ +package com.baeldung.concurrent.threadsafety.services; + +import java.util.concurrent.atomic.AtomicInteger; + +public class AtomicCounter { + + private final AtomicInteger counter = new AtomicInteger(); + + public AtomicCounter() {} + + public void incrementCounter() { + counter.incrementAndGet(); + } + + public synchronized int getCounter() { + return counter.get(); + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/Counter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/Counter.java new file mode 100644 index 0000000000..f7dbc05639 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/Counter.java @@ -0,0 +1,18 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class Counter { + + private volatile int counter; + + public Counter() { + this.counter = 0; + } + + public synchronized void incrementCounter() { + counter += 1; + } + + public int getCounter() { + return counter; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java new file mode 100644 index 0000000000..8ab431fbc3 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class ExtrinsicLockCounter { + + private int counter; + private final Object lock = new Object(); + + public ExtrinsicLockCounter() { + this.counter = 0; + } + + public void incrementCounter() { + synchronized (lock) { + counter += 1; + } + } + + public int getCounter() { + synchronized (lock) { + return counter; + } + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/MessageService.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/MessageService.java new file mode 100644 index 0000000000..33981381ea --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/MessageService.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class MessageService { + + private final String message; + + public MessageService(String message) { + this.message = message; + } + + public String getMesssage() { + return message; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantLockCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantLockCounter.java new file mode 100644 index 0000000000..717f0717af --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantLockCounter.java @@ -0,0 +1,26 @@ +package com.baeldung.concurrent.threadsafety.services; + +import java.util.concurrent.locks.ReentrantLock; + +public class ReentrantLockCounter { + + private int counter; + private final ReentrantLock reLock = new ReentrantLock(true); + + public ReentrantLockCounter() { + this.counter = 0; + } + + public void incrementCounter() { + reLock.lock(); + try { + counter += 1; + } finally { + reLock.unlock(); + } + } + + public int getCounter() { + return counter; + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantReadWriteLockCounter.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantReadWriteLockCounter.java new file mode 100644 index 0000000000..f740c938b1 --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ReentrantReadWriteLockCounter.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.threadsafety.services; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class ReentrantReadWriteLockCounter { + + private int counter; + private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); + private final Lock readLock = rwLock.readLock(); + private final Lock writeLock = rwLock.writeLock(); + + public ReentrantReadWriteLockCounter() { + this.counter = 0; + } + + public void incrementCounter() { + writeLock.lock(); + try { + counter += 1; + } finally { + writeLock.unlock(); + } + } + + public int getCounter() { + readLock.lock(); + try { + return counter; + } finally { + readLock.unlock(); + } + } +} diff --git a/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/StateHolder.java b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/StateHolder.java new file mode 100644 index 0000000000..5bbff9f39c --- /dev/null +++ b/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/StateHolder.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.threadsafety.services; + +public class StateHolder { + + private final String state; + + public StateHolder(String state) { + this.state = state; + } + + public String getState() { + return state; + } +} 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/core-java-concurrency-basic/src/main/resources/logback.xml b/core-java-concurrency-basic/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-concurrency-basic/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-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/CounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/CounterTest.java new file mode 100644 index 0000000000..3abbb1bdad --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/CounterTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.concurrent.threadsafety.callables.CounterCallable; +import com.baeldung.concurrent.threadsafety.services.Counter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class CounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + Counter counter = new Counter(); + Future future1 = (Future) executorService.submit(new CounterCallable(counter)); + Future future2 = (Future) executorService.submit(new CounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ExtrinsicLockCounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ExtrinsicLockCounterTest.java new file mode 100644 index 0000000000..dba90f5b74 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ExtrinsicLockCounterTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class ExtrinsicLockCounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + ExtrinsicLockCounter counter = new ExtrinsicLockCounter(); + Future future1 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); + Future future2 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MathUtilsTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MathUtilsTest.java new file mode 100644 index 0000000000..8f3f574b03 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MathUtilsTest.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import com.baeldung.concurrent.threadsafety.mathutils.MathUtils; +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class MathUtilsTest { + + @Test + public void whenCalledFactorialMethod_thenCorrect() { + assertThat(MathUtils.factorial(2)).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MessageServiceTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MessageServiceTest.java new file mode 100644 index 0000000000..8f1f1a8754 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/MessageServiceTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable; +import com.baeldung.concurrent.threadsafety.services.MessageService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class MessageServiceTest { + + @Test + public void whenCalledgetMessage_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + MessageService messageService = new MessageService("Welcome to Baeldung!"); + Future future1 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + Future future2 = (Future) executorService.submit(new MessageServiceCallable(messageService)); + + assertThat(future1.get()).isEqualTo("Welcome to Baeldung!"); + assertThat(future2.get()).isEqualTo("Welcome to Baeldung!"); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantLockCounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantLockCounterTest.java new file mode 100644 index 0000000000..05c721ab26 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantLockCounterTest.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ReentrantLockCounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + ReentrantLockCounter counter = new ReentrantLockCounter(); + Future future1 = (Future) executorService.submit(new ReentrantLockCounterCallable(counter)); + Future future2 = (Future) executorService.submit(new ReentrantLockCounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } +} diff --git a/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantReadWriteLockCounterTest.java b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantReadWriteLockCounterTest.java new file mode 100644 index 0000000000..c56137ce04 --- /dev/null +++ b/core-java-concurrency-basic/src/test/com/baeldung/concurrent/threadsafety/tests/ReentrantReadWriteLockCounterTest.java @@ -0,0 +1,24 @@ +package com.baeldung.concurrent.threadsafety.tests; + +import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable; +import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class ReentrantReadWriteLockCounterTest { + + @Test + public void whenCalledIncrementCounter_thenCorrect() throws Exception { + ExecutorService executorService = Executors.newFixedThreadPool(2); + ReentrantReadWriteLockCounter counter = new ReentrantReadWriteLockCounter(); + Future future1 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(counter)); + Future future2 = (Future) executorService.submit(new ReentranReadWriteLockCounterCallable(counter)); + + assertThat(future1.get()).isEqualTo(1); + assertThat(future2.get()).isEqualTo(2); + } + +} 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/core-java-concurrency-basic/src/test/resources/.gitignore b/core-java-concurrency-basic/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-concurrency-basic/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-io/README.md b/core-java-io/README.md index 3d028783ed..2ad980ca6a 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -35,3 +35,5 @@ - [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/csv/WriteCsvFileExample.java b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java new file mode 100644 index 0000000000..fd3678d2c5 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java @@ -0,0 +1,29 @@ +package com.baeldung.csv; + +import java.io.BufferedWriter; +import java.io.IOException; + +public class WriteCsvFileExample { + + public void writeLine(BufferedWriter writer, String[] data) throws IOException { + StringBuilder csvLine = new StringBuilder(); + + for (int i = 0; i < data.length; i++) { + if (i > 0) { + csvLine.append(","); + } + csvLine.append(escapeSpecialCharacters(data[i])); + } + + writer.write(csvLine.toString()); + } + + public String escapeSpecialCharacters(String data) { + String escapedData = data.replaceAll("\\R", " "); + if (data.contains(",") || data.contains("\"") || data.contains("'")) { + data = data.replace("\"", "\"\""); + escapedData = "\"" + data + "\""; + } + return escapedData; + } +} 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-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java new file mode 100644 index 0000000000..4ac84f939d --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.csv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class WriteCsvFileExampleUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class); + + private static final String CSV_FILE_NAME = "src/test/resources/exampleOutput.csv"; + private WriteCsvFileExample csvExample; + + @Before + public void setupClass() { + csvExample = new WriteCsvFileExample(); + } + + @Test + public void givenCommaContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() { + String data = "three,two,one"; + String escapedData = csvExample.escapeSpecialCharacters(data); + + String expectedData = "\"three,two,one\""; + assertEquals(expectedData, escapedData); + } + + @Test + public void givenQuoteContainingData_whenEscapeSpecialCharacters_stringReturnedFormatted() { + String data = "She said \"Hello\""; + String escapedData = csvExample.escapeSpecialCharacters(data); + + String expectedData = "\"She said \"\"Hello\"\"\""; + assertEquals(expectedData, escapedData); + } + + @Test + public void givenNewlineContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() { + String dataNewline = "This contains\na newline"; + String dataCarriageReturn = "This contains\r\na newline and carriage return"; + String escapedDataNl = csvExample.escapeSpecialCharacters(dataNewline); + String escapedDataCr = csvExample.escapeSpecialCharacters(dataCarriageReturn); + + String expectedData = "This contains a newline"; + assertEquals(expectedData, escapedDataNl); + String expectedDataCr = "This contains a newline and carriage return"; + assertEquals(expectedDataCr, escapedDataCr); + } + + @Test + public void givenNonSpecialData_whenEscapeSpecialCharacters_stringReturnedUnchanged() { + String data = "This is nothing special"; + String returnedData = csvExample.escapeSpecialCharacters(data); + + assertEquals(data, returnedData); + } + + @Test + public void givenBufferedWriter_whenWriteLine_thenOutputCreated() { + List dataLines = new ArrayList(); + dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" }); + dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" }); + + File csvOutputFile = new File(CSV_FILE_NAME); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvOutputFile))) { + for (Iterator dataIterator = dataLines.iterator(); dataIterator.hasNext();) { + csvExample.writeLine(writer, dataIterator.next()); + if (dataIterator.hasNext()) { + writer.newLine(); + } + } + writer.flush(); + } catch (IOException e) { + LOG.error("IOException " + e.getMessage()); + } + + assertTrue(csvOutputFile.exists()); + } +} 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-io/src/test/resources/exampleOutput.csv b/core-java-io/src/test/resources/exampleOutput.csv new file mode 100644 index 0000000000..45c37f3a3b --- /dev/null +++ b/core-java-io/src/test/resources/exampleOutput.csv @@ -0,0 +1,2 @@ +John,Doe,38,Comment Data Another line of comment data +Jane,"Doe, Jr.",19,"She said ""I'm being quoted""" \ No newline at end of file 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-lang/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-lang/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-lang/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-lang/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/src/main/java/com/baeldung/equalshashcode/Money.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Money.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/Money.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Money.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/Team.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Team.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/Team.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Team.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/Voucher.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Voucher.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/Voucher.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/Voucher.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongTeam.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongTeam.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongTeam.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongTeam.java diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java b/core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java similarity index 100% rename from core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java rename to core-java-lang-oop/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java 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/core-java-lang-oop/src/main/resources/logback.xml b/core-java-lang-oop/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-lang-oop/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-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-lang/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-lang/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/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java diff --git a/core-java-lang/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java b/core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java similarity index 100% rename from core-java-lang/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java rename to core-java-lang-oop/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java 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 69209bb193..7af962558d 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,12 +30,8 @@ - [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) -- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors) - [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name) -- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts) +- [Java Compound Operators](https://www.baeldung.com/java-compound-operators) +- [Guide to Java Packages](https://www.baeldung.com/java-packages) \ No newline at end of file diff --git a/core-java/native/nativedatetimeutils.dll b/core-java-lang/native/nativedatetimeutils.dll similarity index 100% rename from core-java/native/nativedatetimeutils.dll rename to core-java-lang/native/nativedatetimeutils.dll diff --git a/core-java-lang/pom.xml b/core-java-lang/pom.xml index 2f307859f1..283acab775 100644 --- a/core-java-lang/pom.xml +++ b/core-java-lang/pom.xml @@ -56,22 +56,11 @@ ${assertj-core.version} test - - org.springframework - spring-web - ${springframework.spring-web.version} - javax.mail mail ${javax.mail.version} - - nl.jqno.equalsverifier - equalsverifier - ${equalsverifier.version} - test - @@ -82,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 @@ -420,17 +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 - 3.0.3 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 index 83f2a27ea7..bc4515bfc7 100644 --- a/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java +++ b/core-java-lang/src/main/java/com/baeldung/controlstructures/Loops.java @@ -30,6 +30,16 @@ public class Loops { } 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. @@ -45,6 +55,55 @@ public class Loops { } } + /** + * 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. @@ -70,4 +129,29 @@ public class Loops { } } + /** + * 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/enums/values/Element1.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element1.java new file mode 100644 index 0000000000..6c80adacb1 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/enums/values/Element1.java @@ -0,0 +1,17 @@ +package com.baeldung.enums.values; + +/** + * This is a simple enum of periodic table elements + */ +public enum Element1 { + H, + HE, + LI, + BE, + B, + C, + N, + O, + F, + NE +} diff --git a/core-java-lang/src/main/java/com/baeldung/enums/values/Element2.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element2.java new file mode 100644 index 0000000000..28bf3a475a --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/enums/values/Element2.java @@ -0,0 +1,52 @@ +package com.baeldung.enums.values; + +/** + * The simple enum has been enhanced to add the name of the element. + */ +public enum Element2 { + H("Hydrogen"), + HE("Helium"), + LI("Lithium"), + BE("Beryllium"), + B("Boron"), + C("Carbon"), + N("Nitrogen"), + O("Oxygen"), + F("Flourine"), + NE("Neon"); + + /** a final variable to store the label, which can't be changed */ + public final String label; + + /** + * A private constructor that sets the label. + * @param label + */ + private Element2(String label) { + this.label = label; + } + + /** + * Look up Element2 instances by the label field. This implementation iterates through + * the values() list to find the label. + * @param label The label to look up + * @return The Element2 instance with the label, or null if not found. + */ + public static Element2 valueOfLabel(String label) { + for (Element2 e2 : values()) { + if (e2.label.equals(label)) { + return e2; + } + } + return null; + } + + /** + * Override the toString() method to return the label instead of the declared name. + * @return + */ + @Override + public String toString() { + return this.label; + } +} diff --git a/core-java-lang/src/main/java/com/baeldung/enums/values/Element3.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element3.java new file mode 100644 index 0000000000..cb98695de8 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/enums/values/Element3.java @@ -0,0 +1,63 @@ +package com.baeldung.enums.values; + +import java.util.HashMap; +import java.util.Map; + +/** + * A Map has been added to cache labels for faster lookup. + */ +public enum Element3 { + H("Hydrogen"), + HE("Helium"), + LI("Lithium"), + BE("Beryllium"), + B("Boron"), + C("Carbon"), + N("Nitrogen"), + O("Oxygen"), + F("Flourine"), + NE("Neon"); + + /** + * A map to cache labels and their associated Element3 instances. + * Note that this only works if the labels are all unique! + */ + private static final Map BY_LABEL = new HashMap<>(); + + /** populate the BY_LABEL cache */ + static { + for (Element3 e3 : values()) { + BY_LABEL.put(e3.label, e3); + } + } + + /** a final variable to store the label, which can't be changed */ + public final String label; + + /** + * A private constructor that sets the label. + * @param label + */ + private Element3(String label) { + this.label = label; + } + + /** + * Look up Element2 instances by the label field. This implementation finds the + * label in the BY_LABEL cache. + * @param label The label to look up + * @return The Element3 instance with the label, or null if not found. + */ + public static Element3 valueOfLabel(String label) { + return BY_LABEL.get(label); + } + + /** + * Override the toString() method to return the label instead of the declared name. + * @return + */ + @Override + public String toString() { + return this.label; + } +} diff --git a/core-java-lang/src/main/java/com/baeldung/enums/values/Element4.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Element4.java new file mode 100644 index 0000000000..89c45f9d1b --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/enums/values/Element4.java @@ -0,0 +1,95 @@ +package com.baeldung.enums.values; + +import java.util.HashMap; +import java.util.Map; + +/** + * Multiple fields have been added and the Labeled interface is implemented. + */ +public enum Element4 implements Labeled { + H("Hydrogen", 1, 1.008f), + HE("Helium", 2, 4.0026f), + LI("Lithium", 3, 6.94f), + BE("Beryllium", 4, 9.01722f), + B("Boron", 5, 10.81f), + C("Carbon", 6, 12.011f), + N("Nitrogen", 7, 14.007f), + O("Oxygen", 8, 15.999f), + F("Flourine", 9, 18.998f), + NE("Neon", 10, 20.180f); + /** + * Maps cache labels and their associated Element3 instances. + * Note that this only works if the values are all unique! + */ + private static final Map BY_LABEL = new HashMap<>(); + private static final Map BY_ATOMIC_NUMBER = new HashMap<>(); + private static final Map BY_ATOMIC_WEIGHT = new HashMap<>(); + + /** populate the caches */ + static { + for (Element4 e4 : values()) { + BY_LABEL.put(e4.label, e4); + BY_ATOMIC_NUMBER.put(e4.atomicNumber, e4); + BY_ATOMIC_WEIGHT.put(e4.atomicWeight, e4); + } + } + + /** final variables to store the values, which can't be changed */ + public final String label; + public final int atomicNumber; + public final float atomicWeight; + + private Element4(String label, int atomicNumber, float atomicWeight) { + this.label = label; + this.atomicNumber = atomicNumber; + this.atomicWeight = atomicWeight; + } + + /** + * Implement the Labeled interface. + * @return the label value + */ + @Override + public String label() { + return label; + } + + /** + * Look up Element2 instances by the label field. This implementation finds the + * label in the BY_LABEL cache. + * @param label The label to look up + * @return The Element4 instance with the label, or null if not found. + */ + public static Element4 valueOfLabel(String label) { + return BY_LABEL.get(label); + } + + /** + * Look up Element2 instances by the atomicNumber field. This implementation finds the + * atomicNUmber in the cache. + * @param number The atomicNumber to look up + * @return The Element4 instance with the label, or null if not found. + */ + public static Element4 valueOfAtomicNumber(int number) { + return BY_ATOMIC_NUMBER.get(number); + } + + /** + * Look up Element2 instances by the atomicWeight field. This implementation finds the + * atomic weight in the cache. + * @param weight the atomic weight to look up + * @return The Element4 instance with the label, or null if not found. + */ + public static Element4 valueOfAtomicWeight(float weight) { + return BY_ATOMIC_WEIGHT.get(weight); + } + + /** + * Override the toString() method to return the label instead of the declared name. + * @return + */ + @Override + public String toString() { + return this.label; + } +} diff --git a/core-java-lang/src/main/java/com/baeldung/enums/values/Labeled.java b/core-java-lang/src/main/java/com/baeldung/enums/values/Labeled.java new file mode 100644 index 0000000000..e41d6525f1 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/enums/values/Labeled.java @@ -0,0 +1,5 @@ +package com.baeldung.enums.values; + +public interface Labeled { + String label(); +} diff --git a/core-java-lang/src/main/java/com/baeldung/interfaces/Box.java b/core-java-lang/src/main/java/com/baeldung/interfaces/Box.java new file mode 100644 index 0000000000..0bb6560465 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/Box.java @@ -0,0 +1,5 @@ +package com.baeldung.interfaces; + +public interface Box extends HasColor { + int getHeight(); +} diff --git a/core-java-lang/src/main/java/com/baeldung/interfaces/Employee.java b/core-java-lang/src/main/java/com/baeldung/interfaces/Employee.java new file mode 100644 index 0000000000..8c6bd3f7f3 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/Employee.java @@ -0,0 +1,14 @@ +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-lang/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java b/core-java-lang/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java new file mode 100644 index 0000000000..5c841b7c2b --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/EmployeeSalaryComparator.java @@ -0,0 +1,17 @@ +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-lang/src/main/java/com/baeldung/interfaces/HasColor.java b/core-java-lang/src/main/java/com/baeldung/interfaces/HasColor.java new file mode 100644 index 0000000000..d9688ea866 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/HasColor.java @@ -0,0 +1,4 @@ +package com.baeldung.interfaces; + +public interface HasColor { +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java similarity index 83% rename from core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java rename to core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java index fb0d36e3e0..d9b30a1e7b 100644 --- a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Car.java @@ -1,6 +1,7 @@ package com.baeldung.interfaces.multiinheritance; -public class Vehicle implements Fly, Transform { +public class Car implements Fly,Transform { + @Override public void fly() { System.out.println("I can Fly!!"); diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java similarity index 69% rename from core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java rename to core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java index d84182aec6..611e51c67b 100644 --- a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java @@ -1,5 +1,6 @@ package com.baeldung.interfaces.multiinheritance; -public abstract interface Fly{ +public interface Fly { + void fly(); } diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java similarity index 52% rename from core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java rename to core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java index a18bbafdc1..8bdba43a05 100644 --- a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java @@ -1,5 +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-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java new file mode 100644 index 0000000000..be25e112ee --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java @@ -0,0 +1,4 @@ +package com.baeldung.interfaces.multiinheritance; + +public abstract class Vehicle implements Transform { +} diff --git a/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java new file mode 100644 index 0000000000..b4d97bd53a --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java @@ -0,0 +1,9 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Circle implements Shape { + + @Override + public String name() { + return "Circle"; + } +} diff --git a/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/MainTestClass.java b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/MainTestClass.java new file mode 100644 index 0000000000..5cce3c3af0 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/MainTestClass.java @@ -0,0 +1,20 @@ +package com.baeldung.interfaces.polymorphysim; + +import java.util.ArrayList; +import java.util.List; + +public class MainTestClass { + + public static void main(String[] args) { + List shapes = new ArrayList<>(); + Shape circleShape = new Circle(); + Shape squareShape = new Square(); + + shapes.add(circleShape); + shapes.add(squareShape); + + for (Shape shape : shapes) { + System.out.println(shape.name()); + } + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java similarity index 51% rename from core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java rename to core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java index fcb0c65e7b..885dc73de2 100644 --- a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java @@ -1,6 +1,6 @@ package com.baeldung.interfaces.polymorphysim; public interface Shape { - public abstract String name(); - public abstract double area(); + + String name(); } diff --git a/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java new file mode 100644 index 0000000000..c17bdd902d --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java @@ -0,0 +1,9 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Square implements Shape { + + @Override + public String name() { + return "Square"; + } +} diff --git a/core-java/src/main/java/com/baeldung/nativekeyword/DateTimeUtils.java b/core-java-lang/src/main/java/com/baeldung/nativekeyword/DateTimeUtils.java similarity index 100% rename from core-java/src/main/java/com/baeldung/nativekeyword/DateTimeUtils.java rename to core-java-lang/src/main/java/com/baeldung/nativekeyword/DateTimeUtils.java diff --git a/core-java/src/main/java/com/baeldung/nativekeyword/NativeMainApp.java b/core-java-lang/src/main/java/com/baeldung/nativekeyword/NativeMainApp.java similarity index 100% rename from core-java/src/main/java/com/baeldung/nativekeyword/NativeMainApp.java rename to core-java-lang/src/main/java/com/baeldung/nativekeyword/NativeMainApp.java diff --git a/core-java-lang/src/test/java/com/baeldung/enums/values/Element1UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element1UnitTest.java new file mode 100644 index 0000000000..ab3e684230 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/enums/values/Element1UnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.enums.values; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author chris + */ +public class Element1UnitTest { + + public Element1UnitTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test + public void whenAccessingToString_thenItShouldEqualName() { + for (Element1 e1 : Element1.values()) { + assertEquals(e1.name(), e1.toString()); + } + } + + @Test + public void whenCallingValueOf_thenReturnTheCorrectEnum() { + for (Element1 e1 : Element1.values()) { + assertSame(e1, Element1.valueOf(e1.name())); + } + } +} diff --git a/core-java-lang/src/test/java/com/baeldung/enums/values/Element2UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element2UnitTest.java new file mode 100644 index 0000000000..02995a2f41 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/enums/values/Element2UnitTest.java @@ -0,0 +1,59 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.enums.values; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author chris + */ +public class Element2UnitTest { + private static final Logger LOGGER = LoggerFactory.getLogger(Element2UnitTest.class); + + public Element2UnitTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test + public void whenLocatebyLabel_thenReturnCorrectValue() { + for (Element2 e2 : Element2.values()) { + assertSame(e2, Element2.valueOfLabel(e2.label)); + } + } + + /** + * Test of toString method, of class Element2. + */ + @Test + public void whenCallingToString_thenReturnLabel() { + for (Element2 e2 : Element2.values()) { + assertEquals(e2.label, e2.toString()); + } + } +} diff --git a/core-java-lang/src/test/java/com/baeldung/enums/values/Element3UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element3UnitTest.java new file mode 100644 index 0000000000..40c76a97b1 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/enums/values/Element3UnitTest.java @@ -0,0 +1,57 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.enums.values; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author chris + */ +public class Element3UnitTest { + + public Element3UnitTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test + public void whenLocatebyLabel_thenReturnCorrectValue() { + for (Element3 e3 : Element3.values()) { + assertSame(e3, Element3.valueOfLabel(e3.label)); + } + } + + /** + * Test of toString method, of class Element3. + */ + @Test + public void whenCallingToString_thenReturnLabel() { + for (Element3 e3 : Element3.values()) { + assertEquals(e3.label, e3.toString()); + } + } + +} diff --git a/core-java-lang/src/test/java/com/baeldung/enums/values/Element4UnitTest.java b/core-java-lang/src/test/java/com/baeldung/enums/values/Element4UnitTest.java new file mode 100644 index 0000000000..d349dcef72 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/enums/values/Element4UnitTest.java @@ -0,0 +1,71 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.enums.values; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author chris + */ +public class Element4UnitTest { + + public Element4UnitTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test + public void whenLocatebyLabel_thenReturnCorrectValue() { + for (Element4 e4 : Element4.values()) { + assertSame(e4, Element4.valueOfLabel(e4.label)); + } + } + + @Test + public void whenLocatebyAtmNum_thenReturnCorrectValue() { + for (Element4 e4 : Element4.values()) { + assertSame(e4, Element4.valueOfAtomicNumber(e4.atomicNumber)); + } + } + + @Test + public void whenLocatebyAtmWt_thenReturnCorrectValue() { + for (Element4 e4 : Element4.values()) { + assertSame(e4, Element4.valueOfAtomicWeight(e4.atomicWeight)); + } + } + + /** + * Test of toString method, of class Element4. + */ + @Test + public void whenCallingToString_thenReturnLabel() { + for (Element4 e4 : Element4.values()) { + assertEquals(e4.label, e4.toString()); + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/nativekeyword/DateTimeUtilsManualTest.java b/core-java-lang/src/test/java/com/baeldung/nativekeyword/DateTimeUtilsManualTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/nativekeyword/DateTimeUtilsManualTest.java rename to core-java-lang/src/test/java/com/baeldung/nativekeyword/DateTimeUtilsManualTest.java diff --git a/core-java-networking/README.md b/core-java-networking/README.md index 626ea794e6..b2367782b6 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -5,3 +5,12 @@ ### 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 index 178295e1ec..d9c7c691e9 100644 --- a/core-java-networking/pom.xml +++ b/core-java-networking/pom.xml @@ -13,7 +13,37 @@ ../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/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/core-java-networking/src/main/resources/logback.xml b/core-java-networking/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-networking/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/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-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/flightrecorder/FlightRecorder.java b/core-java-perf/src/main/java/com/baeldung/flightrecorder/FlightRecorder.java new file mode 100644 index 0000000000..02c3e96124 --- /dev/null +++ b/core-java-perf/src/main/java/com/baeldung/flightrecorder/FlightRecorder.java @@ -0,0 +1,32 @@ +package com.baeldung.flightrecorder; + +import java.util.ArrayList; +import java.util.List; + +/** + * Simple program that illustrates how to use Java Flight Recorder. + * + * This programs creates a list, inserts objects in it until + * an OutOfMemoryError is thrown. + * + */ +public class FlightRecorder { + + public static void main(String[] args) { + List items = new ArrayList<>(1); + try { + while (true) { + items.add(new Object()); + } + } catch (OutOfMemoryError e) { + System.out.println(e.getMessage()); + } + assert items.size() > 0; + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/gc/VerboseGarbageCollectorRunner.java b/core-java-perf/src/main/java/com/baeldung/gc/VerboseGarbageCollectorRunner.java similarity index 100% rename from core-java/src/main/java/com/baeldung/gc/VerboseGarbageCollectorRunner.java rename to core-java-perf/src/main/java/com/baeldung/gc/VerboseGarbageCollectorRunner.java 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/core-java-perf/src/main/resources/logback.xml b/core-java-perf/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-perf/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/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-security/src/main/java/com/baeldung/ssl/EnableTLSv12.java b/core-java-security/src/main/java/com/baeldung/ssl/EnableTLSv12.java new file mode 100644 index 0000000000..aa70b11584 --- /dev/null +++ b/core-java-security/src/main/java/com/baeldung/ssl/EnableTLSv12.java @@ -0,0 +1,115 @@ +package com.baeldung.ssl; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EnableTLSv12 { + + private final Logger logger = LoggerFactory.getLogger(EnableTLSv12.class); + + public String url = ""; + public Integer port = null; + + public EnableTLSv12() { + } + + public static void main(String[] args) throws IOException, KeyManagementException, NoSuchAlgorithmException { + EnableTLSv12 enableTLSv12 = new EnableTLSv12(); + if (args.length != 2) { + System.out.println("Provide the server url and the secure port:"); + System.exit(-1); + } + enableTLSv12.setHost(args); + enableTLSv12.setPort(args); + enableTLSv12.enableTLSv12UsingHttpConnection(); + enableTLSv12.enableTLSv12UsingProtocol(); + enableTLSv12.enableTLSv12UsingSSLContext(); + enableTLSv12.enableTLSv12UsingSSLParameters(); + } + + private void setPort(String[] args) { + url = args[0]; + } + + private void setHost(String[] args) { + String portNumber = args[1]; + port = Integer.parseInt(portNumber); + } + + private void handleCommunication(SSLSocket socket, String usedTLSProcess) throws IOException { + logger.debug("Enabled TLS v1.2 on " + usedTLSProcess); + try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { + out.println("GET / HTTP/1.0"); + out.println(); + out.flush(); + if (out.checkError()) { + logger.error("SSLSocketClient: java.io.PrintWriter error"); + return; + } + + String inputLine; + while ((inputLine = in.readLine()) != null) + logger.info(inputLine); + } + } + + public void enableTLSv12UsingSSLParameters() throws UnknownHostException, IOException { + SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url.trim(), port); + SSLParameters params = new SSLParameters(); + params.setProtocols(new String[] { "TLSv1.2" }); + sslSocket.setSSLParameters(params); + sslSocket.startHandshake(); + handleCommunication(sslSocket, "SSLSocketFactory-SSLParameters"); + } + + public void enableTLSv12UsingProtocol() throws IOException { + SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(url, port); + sslSocket.setEnabledProtocols(new String[] { "TLSv1.2" }); + sslSocket.startHandshake(); + handleCommunication(sslSocket, "SSLSocketFactory-EnabledProtocols"); + } + + public void enableTLSv12UsingHttpConnection() throws IOException, NoSuchAlgorithmException, KeyManagementException { + URL urls = new URL("https://" + url + ":" + port); + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, new SecureRandom()); + HttpsURLConnection connection = (HttpsURLConnection) urls.openConnection(); + connection.setSSLSocketFactory(sslContext.getSocketFactory()); + try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String input; + while ((input = br.readLine()) != null) { + logger.info(input); + } + } + logger.debug("Created TLSv1.2 connection on HttpsURLConnection"); + } + + public void enableTLSv12UsingSSLContext() throws NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException { + SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + sslContext.init(null, null, new SecureRandom()); + SSLSocketFactory socketFactory = sslContext.getSocketFactory(); + SSLSocket socket = (SSLSocket) socketFactory.createSocket(url, port); + handleCommunication(socket, "SSLContext"); + } + +} 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 20f6ef5ea7..5aee69d9a9 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -5,90 +5,44 @@ ### 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) -- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order) +- [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) -- [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) - [Graphs in Java](https://www.baeldung.com/java-graphs) +- [Console I/O in Java](http://www.baeldung.com/java-console-input-output) +- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) diff --git a/core-java/pom.xml b/core-java/pom.xml index 64345ab14c..6c58653d5a 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -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/curltojava/JavaCurlExamples.java b/core-java/src/main/java/com/baeldung/curltojava/JavaCurlExamples.java new file mode 100644 index 0000000000..166b0ecb13 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/curltojava/JavaCurlExamples.java @@ -0,0 +1,29 @@ +package com.baeldung.curltojava; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class JavaCurlExamples { + + public static String inputStreamToString(InputStream inputStream) { + final int bufferSize = 8 * 1024; + byte[] buffer = new byte[bufferSize]; + final StringBuilder builder = new StringBuilder(); + try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, bufferSize)) { + while (bufferedInputStream.read(buffer) != -1) { + builder.append(new String(buffer)); + } + } catch (IOException ex) { + Logger.getLogger(JavaCurlExamples.class.getName()).log(Level.SEVERE, null, ex); + } + return builder.toString(); + } + + public static void consumeInputStream(InputStream inputStream) { + inputStreamToString(inputStream); + } + +} 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/reflection/Employee.java b/core-java/src/main/java/com/baeldung/reflection/Employee.java new file mode 100644 index 0000000000..833cf26b14 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/reflection/Employee.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection; + +public class Employee extends Person { + + public int employeeId; + +} diff --git a/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java b/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java new file mode 100644 index 0000000000..697ecc1500 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java @@ -0,0 +1,7 @@ +package com.baeldung.reflection; + +public class MonthEmployee extends Employee { + + private double reward; + +} diff --git a/core-java/src/main/java/com/baeldung/reflection/Person.java b/core-java/src/main/java/com/baeldung/reflection/Person.java new file mode 100644 index 0000000000..23b312cdd9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/reflection/Person.java @@ -0,0 +1,8 @@ +package com.baeldung.reflection; + +public class Person { + + public String lastName; + private String firstName; + +} diff --git a/core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesUnitTest.java b/core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesUnitTest.java new file mode 100644 index 0000000000..4e82059f2b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/curltojava/JavaCurlExamplesUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.curltojava; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.junit.Assert; +import org.junit.Test; + +public class JavaCurlExamplesUnitTest { + + + @Test + public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException { + String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\""; + ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" ")); + processBuilder.directory(new File("/home/")); + Process process = processBuilder.start(); + InputStream inputStream = process.getInputStream(); + // Consume the inputStream so the process can exit + JavaCurlExamples.consumeInputStream(inputStream); + int exitCode = process.exitValue(); + + Assert.assertEquals(0, exitCode); + } + + @Test + public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException { + String command = "curl --location --request GET \"https://postman-echo.com/get?foo1=bar1&foo2=bar2\""; + ProcessBuilder processBuilder = new ProcessBuilder(command.replaceAll("\"", "").split(" ")); + processBuilder.directory(new File("/home/")); + Process process = processBuilder.start(); + + // Re-use processBuilder + processBuilder.command(new String[]{"newCommand", "arguments"}); + + Assert.assertEquals(true, process.isAlive()); + } + + @Test + public void whenRequestGet_thenReturnSuccessResponseCode() throws IOException { + String url = "https://postman-echo.com/get?foo1=bar1&foo2=bar2"; + URL urlObj = new URL(url); + HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); + connection.setDoOutput(true); + connection.setInstanceFollowRedirects(false); + connection.setRequestMethod("GET"); + connection.connect(); + + Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java b/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java new file mode 100644 index 0000000000..c051f165f1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java @@ -0,0 +1,128 @@ +package com.baeldung.reflection; + +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.*; + +public class PersonAndEmployeeReflectionUnitTest { + + // Fields names + private static final String LAST_NAME_FIELD = "lastName"; + private static final String FIRST_NAME_FIELD = "firstName"; + private static final String EMPLOYEE_ID_FIELD = "employeeId"; + private static final String MONTH_EMPLOYEE_REWARD_FIELD = "reward"; + + @Test + public void givenPersonClass_whenGetDeclaredFields_thenTwoFields() { + // When + Field[] allFields = Person.class.getDeclaredFields(); + + // Then + assertEquals(2, allFields.length); + + Field lastNameField = allFields[0]; + assertEquals(LAST_NAME_FIELD, lastNameField.getName()); + assertEquals(String.class, lastNameField.getType()); + + Field firstNameField = allFields[1]; + assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); + assertEquals(String.class, firstNameField.getType()); + } + + @Test + public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() { + // When + Field[] allFields = Employee.class.getSuperclass().getDeclaredFields(); + + // Then + assertEquals(2, allFields.length); + + Field lastNameField = allFields[0]; + assertEquals(LAST_NAME_FIELD, lastNameField.getName()); + assertEquals(String.class, lastNameField.getType()); + + Field firstNameField = allFields[1]; + assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); + assertEquals(String.class, firstNameField.getType()); + } + + @Test + public void givenEmployeeClass_whenGetDeclaredFields_thenOneField() { + // When + Field[] allFields = Employee.class.getDeclaredFields(); + + // Then + assertEquals(1, allFields.length); + + Field employeeIdField = allFields[0]; + assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); + assertEquals(int.class, employeeIdField.getType()); + } + + @Test + public void givenEmployeeClass_whenGetDeclaredFieldsOnBothClasses_thenThreeFields() { + // When + Field[] personFields = Employee.class.getSuperclass().getDeclaredFields(); + Field[] employeeFields = Employee.class.getDeclaredFields(); + Field[] allFields = new Field[employeeFields.length + personFields.length]; + Arrays.setAll(allFields, i -> (i < personFields.length ? personFields[i] : employeeFields[i - personFields.length])); + + // Then + assertEquals(3, allFields.length); + + Field lastNameField = allFields[0]; + assertEquals(LAST_NAME_FIELD, lastNameField.getName()); + assertEquals(String.class, lastNameField.getType()); + + Field firstNameField = allFields[1]; + assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); + assertEquals(String.class, firstNameField.getType()); + + Field employeeIdField = allFields[2]; + assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); + assertEquals(int.class, employeeIdField.getType()); + } + + @Test + public void givenMonthEmployeeClass_whenGetAllFields_thenFourFields() { + // When + List allFields = getAllFields(MonthEmployee.class); + + // Then + assertEquals(4, allFields.size()); + + Field lastNameField = allFields.get(0); + assertEquals(LAST_NAME_FIELD, lastNameField.getName()); + assertEquals(String.class, lastNameField.getType()); + + Field firstNameField = allFields.get(1); + assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); + assertEquals(String.class, firstNameField.getType()); + + Field employeeIdField = allFields.get(2); + assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); + assertEquals(int.class, employeeIdField.getType()); + + Field monthEmployeeRewardField = allFields.get(3); + assertEquals(MONTH_EMPLOYEE_REWARD_FIELD, monthEmployeeRewardField.getName()); + assertEquals(double.class, monthEmployeeRewardField.getType()); + } + + public List getAllFields(Class clazz) { + if (clazz == null) { + return Collections.emptyList(); + } + + List result = new ArrayList<>(); + result.addAll(getAllFields(clazz.getSuperclass())); + result.addAll(Arrays.asList(clazz.getDeclaredFields())); + return result; + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java b/core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java deleted file mode 100644 index d952d2383b..0000000000 --- a/core-java/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.string; - - -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class StringReplaceAndRemoveUnitTest { - - - @Test - public void givenTestStrings_whenReplace_thenProcessedString() { - - String master = "Hello World Baeldung!"; - String target = "Baeldung"; - String replacement = "Java"; - String processed = master.replace(target, replacement); - assertTrue(processed.contains(replacement)); - assertFalse(processed.contains(target)); - - } - - @Test - public void givenTestStrings_whenReplaceAll_thenProcessedString() { - - String master2 = "Welcome to Baeldung, Hello World Baeldung"; - String regexTarget= "(Baeldung)$"; - String replacement = "Java"; - String processed2 = master2.replaceAll(regexTarget, replacement); - assertTrue(processed2.endsWith("Java")); - - } - - @Test - public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() { - - String master = "Hello World Baeldung!"; - String target = "Baeldung"; - String replacement = "Java"; - - int startIndex = master.indexOf(target); - int stopIndex = startIndex + target.length(); - - StringBuilder builder = new StringBuilder(master); - - - builder.delete(startIndex, stopIndex); - assertFalse(builder.toString().contains(target)); - - - builder.replace(startIndex, stopIndex, replacement); - assertTrue(builder.toString().contains(replacement)); - - - } - - - @Test - public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() { - - String master = "Hello World Baeldung!"; - String target = "Baeldung"; - String replacement = "Java"; - - String processed = StringUtils.replace(master, target, replacement); - assertTrue(processed.contains(replacement)); - - String master2 = "Hello World Baeldung!"; - String target2 = "baeldung"; - String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement); - assertFalse(processed2.contains(target)); - - } - - - - - - - -} diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 828293ec90..225ad87e87 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) @@ -48,3 +47,7 @@ - [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) +- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts) +- [Operator Overloading in Kotlin](https://www.baeldung.com/kotlin-operator-overloading) +- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) +- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 8b871f28ee..ed79ebc01b 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -72,17 +72,6 @@ injekt-core 1.16.1 - - uy.kohesive.kovert - kovert-vertx - [1.5.0,1.6.0) - - - nl.komponents.kovenant - kovenant - - - 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/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/gson/README.md b/gson/README.md index e1eb155f43..4edd7158d4 100644 --- a/gson/README.md +++ b/gson/README.md @@ -9,3 +9,4 @@ - [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization) - [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file) - [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map) +- [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives) 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/log4j2-example/pom.xml b/guest/log4j2-example/pom.xml index ab55e0b60e..045ff7325b 100644 --- a/guest/log4j2-example/pom.xml +++ b/guest/log4j2-example/pom.xml @@ -41,7 +41,7 @@ - 2.8.8.1 + 2.9.7 2.8.2 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 0f89e07d63..31fead3c42 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -10,3 +10,4 @@ - [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) - [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-maps/README.md b/java-collections-maps/README.md index a6037a3c57..b4ab270448 100644 --- a/java-collections-maps/README.md +++ b/java-collections-maps/README.md @@ -17,3 +17,5 @@ - [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) - [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps) - [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists) +- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) +- [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) diff --git a/java-dates/README.md b/java-dates/README.md index 21e54082f4..ac3166d938 100644 --- a/java-dates/README.md +++ b/java-dates/README.md @@ -26,3 +26,5 @@ - [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 1234a700de..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,8 @@ 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; 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-lite/pom.xml b/java-lite/pom.xml index 03f4e29f4e..b261e521a1 100644 --- a/java-lite/pom.xml +++ b/java-lite/pom.xml @@ -95,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/main/java/com/baeldung/string/DoubleToString.java b/java-numbers/src/main/java/com/baeldung/string/DoubleToString.java similarity index 99% rename from core-java/src/main/java/com/baeldung/string/DoubleToString.java rename to java-numbers/src/main/java/com/baeldung/string/DoubleToString.java index d26d26f3df..dd55ba51ad 100644 --- a/core-java/src/main/java/com/baeldung/string/DoubleToString.java +++ b/java-numbers/src/main/java/com/baeldung/string/DoubleToString.java @@ -38,4 +38,5 @@ public class DoubleToString { return df.format(d); } + } 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/core-java/src/test/java/com/baeldung/string/DoubleToStringUnitTest.java b/java-numbers/src/test/java/com/baeldung/string/DoubleToStringUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/string/DoubleToStringUnitTest.java rename to java-numbers/src/test/java/com/baeldung/string/DoubleToStringUnitTest.java diff --git a/java-streams/README.md b/java-streams/README.md index 2550f08650..33ca2619a8 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -14,3 +14,4 @@ - [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) - [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) - [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) +- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) diff --git a/java-strings/README.md b/java-strings/README.md index 7ff1b0ceea..08fbec35ab 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -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) @@ -43,4 +42,10 @@ - [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) \ No newline at end of file +- [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) +- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) +- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) 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/Pangram.java b/java-strings/src/main/java/com/baeldung/string/Pangram.java new file mode 100644 index 0000000000..c09b0c1d29 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/Pangram.java @@ -0,0 +1,61 @@ +package com.baeldung.string; + +import java.util.Arrays; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Pangram { + private static final int ALPHABET_COUNT = 26; + + public static boolean isPangram(String str) { + if (str == null) + return false; + Boolean[] alphabetMarker = new Boolean[ALPHABET_COUNT]; + Arrays.fill(alphabetMarker, false); + int alphabetIndex = 0; + String strUpper = str.toUpperCase(); + for (int i = 0; i < str.length(); i++) { + if ('A' <= strUpper.charAt(i) && strUpper.charAt(i) <= 'Z') { + alphabetIndex = strUpper.charAt(i) - 'A'; + alphabetMarker[alphabetIndex] = true; + } + } + for (boolean index : alphabetMarker) { + if (!index) + return false; + } + return true; + } + + public static boolean isPangramWithStreams(String str) { + if (str == null) + return false; + + // filtered character stream + String strUpper = str.toUpperCase(); + Stream filteredCharStream = strUpper.chars() + .filter(item -> ((item >= 'A' && item <= 'Z'))) + .mapToObj(c -> (char) c); + Map alphabetMap = filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1)); + + return (alphabetMap.size() == ALPHABET_COUNT); + } + + public static boolean isPerfectPangram(String str) { + if (str == null) + return false; + + // filtered character stream + String strUpper = str.toUpperCase(); + Stream filteredCharStream = strUpper.chars() + .filter(item -> ((item >= 'A' && item <= 'Z'))) + .mapToObj(c -> (char) c); + Map alphabetFrequencyMap = filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + + return (alphabetFrequencyMap.size() == ALPHABET_COUNT && alphabetFrequencyMap.values() + .stream() + .allMatch(item -> item == 1)); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java b/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java index e8d1ce2d8b..2cc67f0b51 100644 --- a/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java +++ b/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java @@ -1,12 +1,20 @@ 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); + + public String replaceCharSubstring(String str, char ch, int index) { + String myString = str.substring(0, index) + ch + str.substring(index + 1); return myString; } - public String replaceCharStringBuilder(String str, char ch, int index) { + 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(); diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java b/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java new file mode 100644 index 0000000000..e914a83f0e --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +public class Customer { + private String firstName; + private String lastName; + + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java new file mode 100644 index 0000000000..1736657276 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +import java.util.Arrays; + +public class CustomerArrayToString extends Customer { + private Order[] orders; + + public Order[] getOrders() { + return orders; + } + public void setOrders(Order[] orders) { + this.orders = orders; + } + @Override + public String toString() { + return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName() + + ", getLastName()=" + getLastName() + "]"; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java new file mode 100644 index 0000000000..9bede1b3fc --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +public class CustomerComplexObjectToString extends Customer { + private Order order; + + public Order getOrder() { + return order; + } + + public void setOrder(Order order) { + this.order = order; + } + + @Override + public String toString() { + return "Customer [order=" + order + ", getFirstName()=" + getFirstName() + + ", getLastName()=" + getLastName() + "]"; + } +} \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java new file mode 100644 index 0000000000..86e08ca447 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java @@ -0,0 +1,19 @@ +package com.baeldung.string.tostring; + +public class CustomerPrimitiveToString extends Customer { + private long balance; + + public long getBalance() { + return balance; + } + + public void setBalance(long balance) { + this.balance = balance; + } + + @Override + public String toString() { + return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName() + + ", getLastName()=" + getLastName() + "]"; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java new file mode 100644 index 0000000000..2da1163c63 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java @@ -0,0 +1,41 @@ +package com.baeldung.string.tostring; + +import java.util.List; + +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; + +public class CustomerReflectionToString extends Customer{ + + private Integer score; + private List orders; + private StringBuffer fullname; + + public Integer getScore() { + return score; + } + + public void setScore(Integer score) { + this.score = score; + } + + public List getOrders() { + return orders; + } + + public void setOrders(List orders) { + this.orders = orders; + } + + public StringBuffer getFullname() { + return fullname; + } + + public void setFullname(StringBuffer fullname) { + this.fullname = fullname; + } + + @Override + public String toString() { + return ReflectionToStringBuilder.toString(this); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java new file mode 100644 index 0000000000..6c7b999045 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java @@ -0,0 +1,39 @@ +package com.baeldung.string.tostring; + +import java.util.List; + +public class CustomerWrapperCollectionToString extends Customer { + private Integer score; + private List orders; + private StringBuffer fullname; + + public Integer getScore() { + return score; + } + + public void setScore(Integer score) { + this.score = score; + } + + public List getOrders() { + return orders; + } + + public void setOrders(List orders) { + this.orders = orders; + } + + public StringBuffer getFullname() { + return fullname; + } + + public void setFullname(StringBuffer fullname) { + this.fullname = fullname; + } + + @Override + public String toString() { + return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname + + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]"; + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Order.java b/java-strings/src/main/java/com/baeldung/string/tostring/Order.java new file mode 100644 index 0000000000..017e2d9bc8 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/tostring/Order.java @@ -0,0 +1,46 @@ +package com.baeldung.string.tostring; + +public class Order { + + private String orderId; + private String desc; + private long value; + private String status; + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public long getValue() { + return value; + } + + public void setValue(long value) { + this.value = value; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + @Override + public String toString() { + return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]"; + } + +} 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/PangramUnitTest.java b/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java new file mode 100644 index 0000000000..36e603b535 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.string; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class PangramUnitTest { + + @Test + public void givenValidString_isPangram_shouldReturnSuccess() { + String input = "Two driven jocks help fax my big quiz"; + assertTrue(Pangram.isPangram(input)); + assertTrue(Pangram.isPangramWithStreams(input)); + } + + @Test + public void givenNullString_isPangram_shouldReturnFailure() { + String input = null; + assertFalse(Pangram.isPangram(input)); + assertFalse(Pangram.isPangramWithStreams(input)); + assertFalse(Pangram.isPerfectPangram(input)); + } + + @Test + public void givenPerfectPangramString_isPerfectPangram_shouldReturnSuccess() { + String input = "abcdefghijklmNoPqrStuVwxyz"; + assertTrue(Pangram.isPerfectPangram(input)); + } + + @Test + public void givenNonPangramString_isPangram_shouldReturnFailure() { + String input = "invalid pangram"; + assertFalse(Pangram.isPangram(input)); + assertFalse(Pangram.isPangramWithStreams(input)); + } + + @Test + public void givenPangram_isPerfectPangram_shouldReturnFailure() { + String input = "Two driven jocks help fax my big quiz"; + assertFalse(Pangram.isPerfectPangram(input)); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java index 07e86bb69b..c234c6953c 100644 --- a/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java @@ -1,23 +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)); + public void whenReplaceCharAtIndexUsingSubstring_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharSubstring("abcde", 'm', 3)); } @Test - public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess(){ - assertEquals("abcme",characterInString.replaceCharStringBuilder("abcde",'m',3)); + public void whenReplaceCharAtIndexUsingCharArray_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharUsingCharArray("abcde", 'm', 3)); } @Test - public void whenReplaceCharAtIndexUsingStringBuffer_thenSuccess(){ - assertEquals("abcme",characterInString.replaceCharStringBuffer("abcde",'m',3)); + 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/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/interview/LocaleUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java new file mode 100644 index 0000000000..1d221056fd --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.string.interview; + +import java.math.BigDecimal; +import java.text.NumberFormat; +import java.util.Locale; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class LocaleUnitTest { + @Test + public void whenUsingLocal_thenCorrectResultsForDifferentLocale() { + Locale usLocale = Locale.US; + BigDecimal number = new BigDecimal(102_300.456d); + + NumberFormat usNumberFormat = NumberFormat.getCurrencyInstance(usLocale); + assertEquals(usNumberFormat.format(number), "$102,300.46"); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java new file mode 100644 index 0000000000..aadfade737 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.interview; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; + +import org.junit.Test; + +public class StringAnagramUnitTest { + public boolean isAnagram(String s1, String s2) { + if(s1.length() != s2.length()) + return false; + + char[] arr1 = s1.toCharArray(); + char[] arr2 = s2.toCharArray(); + + Arrays.sort(arr1); + Arrays.sort(arr2); + + return Arrays.equals(arr1, arr2); + } + + @Test + public void whenTestAnagrams_thenTestingCorrectly() { + assertThat(isAnagram("car", "arc")).isTrue(); + assertThat(isAnagram("west", "stew")).isTrue(); + assertThat(isAnagram("west", "east")).isFalse(); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java new file mode 100644 index 0000000000..2c7ec500fe --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.string.interview; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringChangeCaseUnitTest { + @Test + public void givenString_whenChangingToUppercase_thenCaseChanged() { + String s = "Welcome to Baeldung!"; + assertEquals("WELCOME TO BAELDUNG!", s.toUpperCase()); + } + + + @Test + public void givenString_whenChangingToLowerrcase_thenCaseChanged() { + String s = "Welcome to Baeldung!"; + assertEquals("welcome to baeldung!", s.toLowerCase()); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java new file mode 100644 index 0000000000..6c17643ac8 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.string.interview; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringCountOccurrencesUnitTest { + public int countOccurrences(String s, char c) { + int count = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == c) { + count++; + } + } + return count; + } + + @Test + public void givenString_whenCountingFrequencyOfChar_thenCountCorrect() { + assertEquals(3, countOccurrences("united states", 't')); + } + + public void givenString_whenUsingJava8_thenCountingOfCharCorrect() { + String str = "united states"; + long count = str.chars().filter(ch -> (char)ch == 't').count(); + assertEquals(3, count); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java new file mode 100644 index 0000000000..787017791c --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java @@ -0,0 +1,14 @@ +package com.baeldung.string.interview; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringFormatUnitTest { + @Test + public void givenString_whenUsingStringFormat_thenStringFormatted() { + String title = "Baeldung"; + String formatted = String.format("Title is %s", title); + assertEquals(formatted, "Title is Baeldung"); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java new file mode 100644 index 0000000000..c5bffb7573 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.string.interview; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class StringInternUnitTest { + @Test + public void whenCallingStringIntern_thenStringsInterned() { + String s1 = "Baeldung"; + String s2 = new String("Baeldung"); + String s3 = new String("Baeldung").intern(); + + assertThat(s1 == s2).isFalse(); + assertThat(s1 == s3).isTrue(); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java new file mode 100644 index 0000000000..d44c7478e4 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.string.interview; + +import java.util.StringJoiner; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringJoinerUnitTest { + @Test + public void whenUsingStringJoiner_thenStringsJoined() { + StringJoiner joiner = new StringJoiner(",", "[", "]"); + joiner.add("Red") + .add("Green") + .add("Blue"); + + assertEquals(joiner.toString(), "[Red,Green,Blue]"); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java new file mode 100644 index 0000000000..79ed14cd99 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.interview; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class StringPalindromeUnitTest { + + public boolean isPalindrome(String text) { + int forward = 0; + int backward = text.length() - 1; + while (backward > forward) { + char forwardChar = text.charAt(forward++); + char backwardChar = text.charAt(backward--); + if (forwardChar != backwardChar) + return false; + } + return true; + } + + @Test + public void givenIsPalindromeMethod_whenCheckingString_thenFindIfPalindrome() { + assertThat(isPalindrome("madam")).isTrue(); + assertThat(isPalindrome("radar")).isTrue(); + assertThat(isPalindrome("level")).isTrue(); + + assertThat(isPalindrome("baeldung")).isFalse(); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java new file mode 100644 index 0000000000..bb9b45dc97 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java @@ -0,0 +1,13 @@ +package com.baeldung.string.interview; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StringReverseUnitTest { + @Test + public void whenUsingInbuildMethods_thenStringReversed() { + String reversed = new StringBuilder("baeldung").reverse().toString(); + assertEquals("gnudleab", reversed); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java new file mode 100644 index 0000000000..e1cea62462 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.string.interview; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; + +public class StringSplitUnitTest { + @Test + public void givenCoreJava_whenSplittingStrings_thenSplitted() { + String expected[] = { + "john", + "peter", + "mary" + }; + + String[] splitted = "john,peter,mary".split(","); + assertArrayEquals( expected, splitted ); + } + + @Test + public void givenApacheCommons_whenSplittingStrings_thenSplitted() { + String expected[] = { + "john", + "peter", + "mary" + }; + String[] splitted = StringUtils.split("john peter mary"); + assertArrayEquals( expected, splitted ); + } + + +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java new file mode 100644 index 0000000000..aee4eedcd6 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.string.interview; + +import static org.junit.Assert.assertArrayEquals; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class StringToByteArrayUnitTest { + @Test + public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException { + byte[] byteArray1 = "abcd".getBytes(); + byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII); + byte[] byteArray3 = "ijkl".getBytes("UTF-8"); + byte[] expected1 = new byte[] { 97, 98, 99, 100 }; + byte[] expected2 = new byte[] { 101, 102, 103, 104 }; + byte[] expected3 = new byte[] { 105, 106, 107, 108 }; + + assertArrayEquals(expected1, byteArray1); + assertArrayEquals(expected2, byteArray2); + assertArrayEquals(expected3, byteArray3); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java new file mode 100644 index 0000000000..1322d0fa82 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.string.interview; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; + +import org.junit.Test; + +public class StringToCharArrayUnitTest { + @Test + public void whenConvertingStringToCharArray_thenConversionSuccessful() { + String beforeConvStr = "hello"; + char[] afterConvCharArr = { 'h', 'e', 'l', 'l', 'o' }; + + assertEquals(Arrays.equals(beforeConvStr.toCharArray(), afterConvCharArr), true); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java b/java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java new file mode 100644 index 0000000000..a905438a84 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.string.interview; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class StringToIntegerUnitTest { + @Test + public void givenString_whenParsingInt_shouldConvertToInt() { + String givenString = "42"; + + int result = Integer.parseInt(givenString); + + assertThat(result).isEqualTo(42); + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java new file mode 100644 index 0000000000..9a88416179 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CustomerArrayToStringUnitTest { + private static final String CUSTOMER_ARRAY_TO_STRING + = "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenArray_whenToString_thenCustomerDetails() { + CustomerArrayToString customer = new CustomerArrayToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + Order[] orders = new Order[1]; + orders[0] = new Order(); + orders[0].setOrderId("A1111"); + orders[0].setDesc("Game"); + orders[0].setStatus("In-Shiping"); + customer.setOrders(orders); + + assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString()); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java new file mode 100644 index 0000000000..5ffb0d0e58 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CustomerComplexObjectToStringUnitTest { + private static final String CUSTOMER_COMPLEX_TO_STRING + = "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenComplex_whenToString_thenCustomerDetails() { + CustomerComplexObjectToString customer = new CustomerComplexObjectToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + Order order = new Order(); + order.setOrderId("A1111"); + order.setDesc("Game"); + order.setStatus("In-Shiping"); + customer.setOrder(order); + + assertEquals(CUSTOMER_COMPLEX_TO_STRING, customer.toString()); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java new file mode 100644 index 0000000000..d43733bc60 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CustomerPrimitiveToStringUnitTest { + + private static final String CUSTOMER_PRIMITIVE_TO_STRING + = "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenPrimitive_whenToString_thenCustomerDetails() { + CustomerPrimitiveToString customer = new CustomerPrimitiveToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + customer.setBalance(110); + + assertEquals(CUSTOMER_PRIMITIVE_TO_STRING, customer.toString()); + } +} + diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerReflectionToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerReflectionToStringUnitTest.java new file mode 100644 index 0000000000..77dcab52e6 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerReflectionToStringUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class CustomerReflectionToStringUnitTest { + private static final String CUSTOMER_REFLECTION_TO_STRING = "com.baeldung.string.tostring.CustomerReflectionToString"; + + @Test + public void givenWrapperCollectionStrBuffer_whenReflectionToString_thenCustomerDetails() { + CustomerReflectionToString customer = new CustomerReflectionToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + customer.setScore(8); + + List orders = new ArrayList(); + orders.add("Book"); + orders.add("Pen"); + customer.setOrders(orders); + + StringBuffer fullname = new StringBuffer(); + fullname.append(customer.getLastName()+", "+ customer.getFirstName()); + customer.setFullname(fullname); + + assertTrue(customer.toString().contains(CUSTOMER_REFLECTION_TO_STRING)); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java new file mode 100644 index 0000000000..e04512ff75 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.string.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class CustomerWrapperCollectionToStringUnitTest { + private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING + = "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() { + CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + customer.setScore(8); + + List orders = new ArrayList(); + orders.add("Book"); + orders.add("Pen"); + customer.setOrders(orders); + + StringBuffer fullname = new StringBuffer(); + fullname.append(customer.getLastName()+", "+ customer.getFirstName()); + customer.setFullname(fullname); + + assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString()); + } + +} diff --git a/jee-7/README.md b/jee-7/README.md index a2493e561b..a783e7860e 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -5,3 +5,4 @@ - [Introduction to JAX-WS](http://www.baeldung.com/jax-ws) - [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations) - [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian) +- [Java EE 7 Batch Processing](https://www.baeldung.com/java-ee-7-batch-processing) 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/kotlin-libraries/README.md b/kotlin-libraries/README.md index d1ef77aa46..4110bfe12e 100644 --- a/kotlin-libraries/README.md +++ b/kotlin-libraries/README.md @@ -5,7 +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 ae77a9aa2d..507e5820d4 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -95,6 +95,23 @@ 0.7.3 + + uy.kohesive.kovert + kovert-vertx + [1.5.0,1.6.0) + + + nl.komponents.kovenant + kovenant + + + + + nl.komponents.kovenant + kovenant + 3.3.0 + pom + @@ -110,4 +127,4 @@ 0.10.4 - \ No newline at end of file + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/JsonServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/JsonServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/NoopServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/NoopServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt similarity index 100% rename from core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt rename to kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt diff --git a/core-kotlin/src/main/resources/kovert.conf b/kotlin-libraries/src/main/resources/kovert.conf similarity index 100% rename from core-kotlin/src/main/resources/kovert.conf rename to kotlin-libraries/src/main/resources/kovert.conf diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index f913cf32ca..daf6c8b500 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -442,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/04_Custom/connect-distributed.properties b/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties deleted file mode 100644 index 5b91baddbd..0000000000 --- a/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties +++ /dev/null @@ -1,88 +0,0 @@ -## -# 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 index 333768e4b7..852f400fc6 100644 --- 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 @@ -1,22 +1,14 @@ { - "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" + "name": "mongodb-sink", + "config": { + "connector.class": "at.grahsl.kafka.connect.mongodb.MongoDbSinkConnector", + "tasks.max": 1, + "topics": "connect-custom", + "mongodb.connection.uri": "mongodb://mongo-db/test?retryWrites=true", + "mongodb.collection": "MyCollection", + "key.converter": "org.apache.kafka.connect.json.JsonConverter", + "key.converter.schemas.enable": false, + "value.converter": "org.apache.kafka.connect.json.JsonConverter", + "value.converter.schemas.enable": false } } 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 index 02d87c5ad7..c76d326c0a 100644 --- 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 @@ -3,9 +3,11 @@ "config": { "connector.class": "io.confluent.connect.mqtt.MqttSourceConnector", "tasks.max": 1, - "mqtt.server.uri": "ws://broker.hivemq.com:8000/mqtt", + "mqtt.server.uri": "tcp://mosquitto:1883", "mqtt.topics": "baeldung", "kafka.topic": "connect-custom", - "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter" + "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter", + "confluent.topic.bootstrap.servers": "kafka:9092", + "confluent.topic.replication.factor": 1 } -} +} \ No newline at end of file diff --git a/libraries-data/src/main/kafka-connect/04_Custom/docker-compose.yaml b/libraries-data/src/main/kafka-connect/04_Custom/docker-compose.yaml new file mode 100644 index 0000000000..26cd653335 --- /dev/null +++ b/libraries-data/src/main/kafka-connect/04_Custom/docker-compose.yaml @@ -0,0 +1,94 @@ +version: '3.3' + +services: + mosquitto: + image: eclipse-mosquitto:1.5.5 + hostname: mosquitto + container_name: mosquitto + expose: + - "1883" + ports: + - "1883:1883" + zookeeper: + image: zookeeper:3.4.9 + restart: unless-stopped + hostname: zookeeper + container_name: zookeeper + ports: + - "2181:2181" + environment: + ZOO_MY_ID: 1 + ZOO_PORT: 2181 + ZOO_SERVERS: server.1=zookeeper:2888:3888 + volumes: + - ./zookeeper/data:/data + - ./zookeeper/datalog:/datalog + kafka: + image: confluentinc/cp-kafka:5.1.0 + hostname: kafka + container_name: kafka + ports: + - "9092:9092" + environment: + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092 + KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" + KAFKA_BROKER_ID: 1 + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + volumes: + - ./kafka/data:/var/lib/kafka/data + depends_on: + - zookeeper + kafka-connect: + image: confluentinc/cp-kafka-connect:5.1.0 + hostname: kafka-connect + container_name: kafka-connect + ports: + - "8083:8083" + environment: + CONNECT_BOOTSTRAP_SERVERS: "kafka:9092" + CONNECT_REST_ADVERTISED_HOST_NAME: connect + CONNECT_REST_PORT: 8083 + CONNECT_GROUP_ID: compose-connect-group + CONNECT_CONFIG_STORAGE_TOPIC: docker-connect-configs + CONNECT_OFFSET_STORAGE_TOPIC: docker-connect-offsets + CONNECT_STATUS_STORAGE_TOPIC: docker-connect-status + CONNECT_KEY_CONVERTER: org.apache.kafka.connect.json.JsonConverter + CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter + CONNECT_INTERNAL_KEY_CONVERTER: "org.apache.kafka.connect.json.JsonConverter" + CONNECT_INTERNAL_VALUE_CONVERTER: "org.apache.kafka.connect.json.JsonConverter" + CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: "1" + CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: "1" + CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: "1" + CONNECT_PLUGIN_PATH: '/usr/share/java,/etc/kafka-connect/jars' + CONNECT_CONFLUENT_TOPIC_REPLICATION_FACTOR: 1 + volumes: + - /tmp/custom/jars:/etc/kafka-connect/jars + depends_on: + - zookeeper + - kafka + - mosquitto + mongo-db: + image: mongo:4.0.5 + hostname: mongo-db + container_name: mongo-db + expose: + - "27017" + ports: + - "27017:27017" + command: --bind_ip_all --smallfiles + volumes: + - ./mongo-db:/data + mongoclient: + image: mongoclient/mongoclient:2.2.0 + container_name: mongoclient + hostname: mongoclient + depends_on: + - mongo-db + ports: + - 3000:3000 + environment: + MONGO_URL: "mongodb://mongo-db:27017" + PORT: 3000 + expose: + - "3000" \ No newline at end of file diff --git a/libraries/README.md b/libraries/README.md index c1f16df6b4..b247caedda 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -18,7 +18,6 @@ - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Introduction to Neuroph](http://www.baeldung.com/neuroph) - [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) - [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections) @@ -34,7 +33,6 @@ - [Introduction to Retrofit](http://www.baeldung.com/retrofit) - [Using Pairs in Java](http://www.baeldung.com/java-pairs) - [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) diff --git a/libraries/pom.xml b/libraries/pom.xml index 3a51ff5be0..c7ef64bc59 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -818,7 +818,7 @@ 1.0 4.5.3 - 2.8.5 + 2.9.7 2.92 1.9.26 1.41.0 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/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index d46f92dcd6..924abfd346 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -115,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/README.md b/lombok-custom/README.md new file mode 100644 index 0000000000..bfc784ea7e --- /dev/null +++ b/lombok-custom/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Implementing a Custom Lombok Annotation](https://www.baeldung.com/lombok-custom-annotation) 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/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 e56872b3fd..8046d2034b 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -14,3 +14,7 @@ - [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/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/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractFactory.java b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractFactory.java index 5b4bf08006..88e819c066 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractFactory.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractFactory.java @@ -1,6 +1,5 @@ package com.baeldung.creational.abstractfactory; -public interface AbstractFactory { - Animal getAnimal(String toyType) ; - Color getColor(String colorType); +public interface AbstractFactory { + T create(String type) ; } \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractPatternDriver.java b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractPatternDriver.java index 68759d5aff..c1501091c5 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractPatternDriver.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AbstractPatternDriver.java @@ -6,10 +6,10 @@ public class AbstractPatternDriver { //creating a brown toy dog abstractFactory = FactoryProvider.getFactory("Toy"); - Animal toy = abstractFactory.getAnimal("Dog"); + Animal toy =(Animal) abstractFactory.create("Dog"); abstractFactory = FactoryProvider.getFactory("Color"); - Color color = abstractFactory.getColor("Brown"); + Color color =(Color) abstractFactory.create("Brown"); String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound(); diff --git a/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AnimalFactory.java b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AnimalFactory.java index bbc3eb7a82..4b46261571 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AnimalFactory.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/AnimalFactory.java @@ -1,9 +1,9 @@ package com.baeldung.creational.abstractfactory; -public class AnimalFactory implements AbstractFactory { +public class AnimalFactory implements AbstractFactory { @Override - public Animal getAnimal(String animalType) { + public Animal create(String animalType) { if ("Dog".equalsIgnoreCase(animalType)) { return new Dog(); } else if ("Duck".equalsIgnoreCase(animalType)) { @@ -13,9 +13,4 @@ public class AnimalFactory implements AbstractFactory { return null; } - @Override - public Color getColor(String color) { - throw new UnsupportedOperationException(); - } - } diff --git a/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/ColorFactory.java b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/ColorFactory.java index 8b7e4f8086..3d9c5c18a3 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/ColorFactory.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/creational/abstractfactory/ColorFactory.java @@ -1,9 +1,9 @@ package com.baeldung.creational.abstractfactory; -public class ColorFactory implements AbstractFactory { +public class ColorFactory implements AbstractFactory { @Override - public Color getColor(String colorType) { + public Color create(String colorType) { if ("Brown".equalsIgnoreCase(colorType)) { return new Brown(); } else if ("White".equalsIgnoreCase(colorType)) { @@ -13,9 +13,4 @@ public class ColorFactory implements AbstractFactory { return null; } - @Override - public Animal getAnimal(String toyType) { - throw new UnsupportedOperationException(); - } - } 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/design-patterns/src/test/java/com/baeldung/creational/abstractfactory/AbstractPatternIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/creational/abstractfactory/AbstractPatternIntegrationTest.java index 6d1a4ad8fd..4f02249a4b 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/creational/abstractfactory/AbstractPatternIntegrationTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/creational/abstractfactory/AbstractPatternIntegrationTest.java @@ -11,10 +11,10 @@ public class AbstractPatternIntegrationTest { //creating a brown toy dog abstractFactory = FactoryProvider.getFactory("Toy"); - Animal toy = abstractFactory.getAnimal("Dog"); + Animal toy = (Animal) abstractFactory.create("Dog"); abstractFactory = FactoryProvider.getFactory("Color"); - Color color = abstractFactory.getColor("Brown"); + Color color =(Color) abstractFactory.create("Brown"); String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound(); assertEquals("A Dog with brown color Barks", result); diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index b6e112b5fc..03bdd9b759 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -21,3 +21,11 @@ - [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) +- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager) +- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) +- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one) +- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) +- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) +- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index f5a3a7e4c9..af94025a73 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -1,11 +1,12 @@ - + 4.0.0 com.baeldung hibernate5 0.0.1-SNAPSHOT - hibernate5 + hibernate5 com.baeldung @@ -66,6 +67,12 @@ byte-buddy 1.9.5 + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + @@ -79,12 +86,12 @@ - 5.3.6.Final + 5.3.7.Final 6.0.6 2.2.3 1.4.196 3.8.0 - 2.8.11.3 + 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/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/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 9a90216519..2eea5e60b4 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,4 +2,5 @@ - [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) -- [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) +- [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) +- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index e240ae6d33..976a692699 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -17,6 +17,8 @@ - [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) +- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InsertRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InsertRepository.java deleted file mode 100644 index 6a74e067fe..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InsertRepository.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.dao.repositories; - -public interface InsertRepository { - void insert(S entity); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonEntityManagerInsertRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonEntityManagerInsertRepository.java deleted file mode 100644 index 6d3cbb07df..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonEntityManagerInsertRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.dao.repositories; - -import com.baeldung.domain.Person; - -public interface PersonEntityManagerInsertRepository { - void insert(Person person); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonEntityManagerRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonEntityManagerRepository.java deleted file mode 100644 index cbf3d59620..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonEntityManagerRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.dao.repositories; - -import com.baeldung.domain.Person; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface PersonEntityManagerRepository extends JpaRepository, PersonEntityManagerInsertRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonQueryInsertRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonQueryInsertRepository.java deleted file mode 100644 index be01e9883a..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonQueryInsertRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.dao.repositories; - -import com.baeldung.domain.Person; - -public interface PersonQueryInsertRepository { - void insert(Person person); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonQueryRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonQueryRepository.java deleted file mode 100644 index 1516c38443..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/PersonQueryRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.dao.repositories; - -import com.baeldung.domain.Person; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -@Repository -public interface PersonQueryRepository extends JpaRepository, PersonQueryInsertRepository { - - @Modifying - @Query(value = "INSERT INTO person (id, first_name, last_name) VALUES (:id,:firstName,:lastName)", nativeQuery = true) - void insertWithAnnotation(@Param("id") Long id, @Param("firstName") String firstName, @Param("lastName") String lastName); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonEntityManagerInsertRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonEntityManagerInsertRepositoryImpl.java deleted file mode 100644 index c14cc44125..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonEntityManagerInsertRepositoryImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.dao.repositories.impl; - -import com.baeldung.dao.repositories.PersonEntityManagerInsertRepository; -import com.baeldung.domain.Person; -import org.springframework.transaction.annotation.Transactional; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - -@Transactional -public class PersonEntityManagerInsertRepositoryImpl implements PersonEntityManagerInsertRepository { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public void insert(Person person) { - this.entityManager.persist(person); - } -} - diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonQueryInsertRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonInsertRepository.java similarity index 60% rename from persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonQueryInsertRepositoryImpl.java rename to persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonInsertRepository.java index 341db1615d..d809385456 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonQueryInsertRepositoryImpl.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/impl/PersonInsertRepository.java @@ -1,24 +1,30 @@ package com.baeldung.dao.repositories.impl; -import com.baeldung.dao.repositories.PersonQueryInsertRepository; import com.baeldung.domain.Person; +import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; -@Transactional -public class PersonQueryInsertRepositoryImpl implements PersonQueryInsertRepository { +@Repository +public class PersonInsertRepository { @PersistenceContext private EntityManager entityManager; - @Override - public void insert(Person person) { - entityManager.createNativeQuery("INSERT INTO person (id,first_name, last_name) VALUES (?,?,?)") + @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/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java index 5bb0232e4a..7f54254832 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepository.java @@ -1,6 +1,7 @@ package com.baeldung.dao.repositories.user; import com.baeldung.domain.user.User; + import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -13,7 +14,7 @@ import java.util.Collection; import java.util.List; import java.util.stream.Stream; -public interface UserRepository extends JpaRepository { +public interface UserRepository extends JpaRepository , UserRepositoryCustom{ Stream findAllByName(String name); diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustom.java new file mode 100644 index 0000000000..72c1fd5d00 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustom.java @@ -0,0 +1,10 @@ +package com.baeldung.dao.repositories.user; + +import java.util.List; +import java.util.Set; + +import com.baeldung.domain.user.User; + +public interface UserRepositoryCustom { + List findUserByEmails(Set emails); +} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustomImpl.java new file mode 100644 index 0000000000..9f841caf68 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/user/UserRepositoryCustomImpl.java @@ -0,0 +1,43 @@ +package com.baeldung.dao.repositories.user; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import com.baeldung.domain.user.User; + +public class UserRepositoryCustomImpl implements UserRepositoryCustom { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public List findUserByEmails(Set emails) { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(User.class); + Root user = query.from(User.class); + + Path emailPath = user.get("email"); + + List predicates = new ArrayList<>(); + for (String email : emails) { + + predicates.add(cb.like(emailPath, email)); + + } + query.select(user) + .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); + + return entityManager.createQuery(query) + .getResultList(); + } + +} 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 index 476554f6d6..b248cf8bf1 100644 --- 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 @@ -1,21 +1,24 @@ package com.baeldung.dao.repositories; +import com.baeldung.dao.repositories.impl.PersonInsertRepository; import com.baeldung.domain.Person; import org.junit.Test; -import org.junit.jupiter.api.BeforeEach; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Optional; +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; @@ -24,43 +27,23 @@ public class PersonInsertRepositoryIntegrationTest { private static final Person PERSON = new Person(ID, FIRST_NAME, LAST_NAME); @Autowired - private PersonQueryRepository personQueryRepository; + private PersonInsertRepository personInsertRepository; @Autowired - private PersonEntityManagerRepository personEntityManagerRepository; - - @BeforeEach - public void clearDB() { - personQueryRepository.deleteAll(); - } + private EntityManager entityManager; @Test public void givenPersonEntity_whenInsertWithNativeQuery_ThenPersonIsPersisted() { - insertPerson(); + insertWithQuery(); assertPersonPersisted(); } @Test - public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenDataIntegrityViolationExceptionIsThrown() { - assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> { - insertPerson(); - insertPerson(); - }); - } - - @Test - public void givenPersonEntity_whenInsertWithQueryAnnotation_thenPersonIsPersisted() { - insertPersonWithQueryAnnotation(); - - assertPersonPersisted(); - } - - @Test - public void givenPersonEntity_whenInsertedTwiceWithQueryAnnotation_thenDataIntegrityViolationExceptionIsThrown() { - assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> { - insertPersonWithQueryAnnotation(); - insertPersonWithQueryAnnotation(); + public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenPersistenceExceptionExceptionIsThrown() { + assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> { + insertWithQuery(); + insertWithQuery(); }); } @@ -72,31 +55,27 @@ public class PersonInsertRepositoryIntegrationTest { } @Test - public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenDataIntegrityViolationExceptionIsThrown() { - assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> { + public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenEntityExistsExceptionIsThrown() { + assertThatExceptionOfType(EntityExistsException.class).isThrownBy(() -> { insertPersonWithEntityManager(); insertPersonWithEntityManager(); }); } - private void insertPerson() { - personQueryRepository.insert(PERSON); - } - - private void insertPersonWithQueryAnnotation() { - personQueryRepository.insertWithAnnotation(ID, FIRST_NAME, LAST_NAME); + private void insertWithQuery() { + personInsertRepository.insertWithQuery(PERSON); } private void insertPersonWithEntityManager() { - personEntityManagerRepository.insert(new Person(ID, FIRST_NAME, LAST_NAME)); + personInsertRepository.insertWithEntityManager(new Person(ID, FIRST_NAME, LAST_NAME)); } private void assertPersonPersisted() { - Optional personOptional = personQueryRepository.findById(PERSON.getId()); + Person person = entityManager.find(Person.class, ID); - assertThat(personOptional.isPresent()).isTrue(); - assertThat(personOptional.get().getId()).isEqualTo(PERSON.getId()); - assertThat(personOptional.get().getFirstName()).isEqualTo(PERSON.getFirstName()); - assertThat(personOptional.get().getLastName()).isEqualTo(PERSON.getLastName()); + 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/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java index e29161394b..b05086d00e 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/UserRepositoryIntegrationTest.java @@ -18,7 +18,9 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -274,9 +276,8 @@ public class UserRepositoryIntegrationTest { List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - assertThat(usersSortByName - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); + assertThat(usersSortByName.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); } @Test(expected = PropertyReferenceException.class) @@ -289,9 +290,8 @@ public class UserRepositoryIntegrationTest { List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); - assertThat(usersSortByNameLength - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); } @Test @@ -304,9 +304,8 @@ public class UserRepositoryIntegrationTest { List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - assertThat(usersSortByNameLength - .get(0) - .getName()).isEqualTo(USER_NAME_ADAM); + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); } @Test @@ -320,10 +319,9 @@ public class UserRepositoryIntegrationTest { Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); - assertThat(usersPage - .getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); + assertThat(usersPage.getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); } @Test @@ -337,10 +335,9 @@ public class UserRepositoryIntegrationTest { Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); - assertThat(usersSortByNameLength - .getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); + assertThat(usersSortByNameLength.getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); } @Test @@ -370,6 +367,30 @@ public class UserRepositoryIntegrationTest { assertThat(updatedUsersSize).isEqualTo(2); } + @Test + public void givenUsersInDBWhenFindByEmailsWithDynamicQueryThenReturnCollection() { + + User user1 = new User(); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + Set emails = new HashSet<>(); + emails.add(USER_EMAIL2); + emails.add(USER_EMAIL3); + + Collection usersWithEmails = userRepository.findUserByEmails(emails); + + assertThat(usersWithEmails.size()).isEqualTo(2); + } + @After public void cleanUp() { userRepository.deleteAll(); diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index 75d23f7532..5e287919f1 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -1,6 +1,5 @@ ### Relevant articles -- [@Immutable 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-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/pom.xml b/pom.xml index 2f7212a28c..324f6129db 100644 --- a/pom.xml +++ b/pom.xml @@ -379,10 +379,16 @@ 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-networking + core-java-lang-oop + core-java-networking + core-java-perf core-java-sun core-scala couchbase @@ -638,10 +644,12 @@ spring-boot-logging-log4j2 spring-boot-mvc spring-boot-ops + spring-boot-rest spring-boot-property-exp spring-boot-security spring-boot-testing spring-boot-vue + spring-boot-libraries spring-cloud spring-cloud-bus @@ -656,6 +664,7 @@ spring-dispatcher-servlet spring-drools + spring-ehcache spring-ejb spring-exceptions @@ -875,6 +884,7 @@ spring-data-rest spring-dispatcher-servlet spring-drools + spring-ehcache spring-freemarker persistence-modules/spring-hibernate-3 persistence-modules/spring-hibernate4 @@ -987,7 +997,7 @@ parent-kotlin core-java - core-java-concurrency + core-java-concurrency-advanced core-kotlin jenkins/hello-world @@ -1085,10 +1095,16 @@ 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 @@ -1340,6 +1356,7 @@ spring-boot-logging-log4j2 spring-boot-mvc spring-boot-ops + spring-boot-rest spring-boot-property-exp spring-boot-security spring-boot-vue @@ -1357,6 +1374,7 @@ spring-dispatcher-servlet spring-drools + spring-ehcache spring-ejb spring-exceptions @@ -1530,7 +1548,7 @@ parent-kotlin core-java - core-java-concurrency + core-java-concurrency-advanced core-kotlin jenkins/hello-world @@ -1603,7 +1621,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/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/spring-5-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java index 602ded6b9e..b95517200e 100644 --- a/spring-5-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/reactive/oauth/Spring5ReactiveOauthApplication.java @@ -3,11 +3,13 @@ package com.baeldung.reactive.oauth; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; import org.springframework.web.reactive.function.client.WebClient; +@PropertySource("classpath:default-application.yml") @SpringBootApplication public class Spring5ReactiveOauthApplication { diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/OauthClientApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/OauthClientApplication.java new file mode 100644 index 0000000000..7bae78bb14 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/OauthClientApplication.java @@ -0,0 +1,24 @@ +package com.baeldung.webclient.authorizationcodeclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +/** + * + * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth + * + * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (bael-user/bael-password) and client configurations (bael-client-id/bael-secret) handled by the auth server + * + * @author rozagerardo + * + */ +@PropertySource("classpath:webclient-auth-code-client-application.properties") +@SpringBootApplication +public class OauthClientApplication { + + public static void main(String[] args) { + SpringApplication.run(OauthClientApplication.class, args); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebClientConfig.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebClientConfig.java new file mode 100644 index 0000000000..884a3c145d --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebClientConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.webclient.authorizationcodeclient.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction; +import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; +import org.springframework.web.reactive.function.client.WebClient; + +@Configuration +public class WebClientConfig { + + @Bean + WebClient webClientForAuthorized(ReactiveClientRegistrationRepository clientRegistrations, ServerOAuth2AuthorizedClientRepository authorizedClients) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients); + return WebClient.builder() + .filter(oauth) + .build(); + } +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebSecurityConfig.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebSecurityConfig.java new file mode 100644 index 0000000000..4271ae96cf --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/configuration/WebSecurityConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.webclient.authorizationcodeclient.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@Configuration +public class WebSecurityConfig { + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .authenticated() + .and() + .oauth2Client() + .and() + .formLogin(); + return http.build(); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/web/ClientRestController.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/web/ClientRestController.java new file mode 100644 index 0000000000..c36b7d1dea --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodeclient/web/ClientRestController.java @@ -0,0 +1,53 @@ +package com.baeldung.webclient.authorizationcodeclient.web; + +import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; +import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Mono; + +@RestController +public class ClientRestController { + + private static final String RESOURCE_URI = "http://localhost:8084/retrieve-resource"; + + @Autowired + WebClient webClient; + + @GetMapping("/auth-code") + Mono useOauthWithAuthCode() { + Mono retrievedResource = webClient.get() + .uri(RESOURCE_URI) + .retrieve() + .bodyToMono(String.class); + return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string); + } + + @GetMapping("/auth-code-annotated") + Mono useOauthWithAuthCodeAndAnnotation(@RegisteredOAuth2AuthorizedClient("bael") OAuth2AuthorizedClient authorizedClient) { + Mono retrievedResource = webClient.get() + .uri(RESOURCE_URI) + .attributes(oauth2AuthorizedClient(authorizedClient)) + .retrieve() + .bodyToMono(String.class); + return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string + ". Principal associated: " + authorizedClient.getPrincipalName() + ". Token will expire at: " + authorizedClient.getAccessToken() + .getExpiresAt()); + } + + @GetMapping("/auth-code-explicit-client") + Mono useOauthWithExpicitClient() { + Mono retrievedResource = webClient.get() + .uri(RESOURCE_URI) + .attributes(clientRegistrationId("bael")) + .retrieve() + .bodyToMono(String.class); + return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientApplication.java new file mode 100644 index 0000000000..9dd6dd1bde --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/OauthClientApplication.java @@ -0,0 +1,24 @@ +package com.baeldung.webclient.authorizationcodelogin; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +/** + * + * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth + * + * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (bael-user/bael-password) and client configurations (bael-client-id/bael-secret) handled by the auth server + * + * @author rozagerardo + * + */ +@PropertySource("classpath:webclient-auth-code-login-application.properties") +@SpringBootApplication +public class OauthClientApplication { + + public static void main(String[] args) { + SpringApplication.run(OauthClientApplication.class, args); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebClientConfig.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebClientConfig.java new file mode 100644 index 0000000000..15458cc60a --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebClientConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.webclient.authorizationcodelogin.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction; +import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; +import org.springframework.web.reactive.function.client.WebClient; + +@Configuration +public class WebClientConfig { + + @Bean + @Primary + WebClient webClientForAuthorized(ReactiveClientRegistrationRepository clientRegistrations, ServerOAuth2AuthorizedClientRepository authorizedClients) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients); + oauth.setDefaultOAuth2AuthorizedClient(true); + return WebClient.builder() + .filter(oauth) + .build(); + } + + @Bean + WebClient otherWebClient(ReactiveClientRegistrationRepository clientRegistrations, ServerOAuth2AuthorizedClientRepository authorizedClients) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients); + return WebClient.builder() + .filter(oauth) + .build(); + } +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebSecurityConfig.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebSecurityConfig.java new file mode 100644 index 0000000000..f45fc09222 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/configuration/WebSecurityConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.webclient.authorizationcodelogin.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@Configuration +public class WebSecurityConfig { + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .authenticated() + .and() + .oauth2Login(); + return http.build(); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/web/ClientRestController.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/web/ClientRestController.java new file mode 100644 index 0000000000..55e0096525 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/authorizationcodelogin/web/ClientRestController.java @@ -0,0 +1,68 @@ +package com.baeldung.webclient.authorizationcodelogin.web; + +import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; +import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Mono; + +@RestController +public class ClientRestController { + + private static final String RESOURCE_URI = "http://localhost:8084/retrieve-resource"; + + @Autowired + WebClient webClient; + + @Autowired + @Qualifier("otherWebClient") + WebClient otherWebClient; + + @GetMapping("/auth-code") + Mono useOauthWithAuthCode() { + Mono retrievedResource = webClient.get() + .uri(RESOURCE_URI) + .retrieve() + .bodyToMono(String.class); + return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string); + } + + @GetMapping("/auth-code-no-client") + Mono useOauthWithNoClient() { + // This call will fail, since we don't have the client properly set for this webClient + Mono retrievedResource = otherWebClient.get() + .uri(RESOURCE_URI) + .retrieve() + .bodyToMono(String.class); + return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string); + } + + @GetMapping("/auth-code-annotated") + Mono useOauthWithAuthCodeAndAnnotation(@RegisteredOAuth2AuthorizedClient("bael") OAuth2AuthorizedClient authorizedClient) { + Mono retrievedResource = otherWebClient.get() + .uri(RESOURCE_URI) + .attributes(oauth2AuthorizedClient(authorizedClient)) + .retrieve() + .bodyToMono(String.class); + return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string + ". Principal associated: " + authorizedClient.getPrincipalName() + ". Token will expire at: " + authorizedClient.getAccessToken() + .getExpiresAt()); + } + + @GetMapping("/auth-code-explicit-client") + Mono useOauthWithExpicitClient() { + Mono retrievedResource = otherWebClient.get() + .uri(RESOURCE_URI) + .attributes(clientRegistrationId("bael")) + .retrieve() + .bodyToMono(String.class); + return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/ClientCredentialsOauthApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/ClientCredentialsOauthApplication.java new file mode 100644 index 0000000000..d1b9f7f744 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/ClientCredentialsOauthApplication.java @@ -0,0 +1,26 @@ +package com.baeldung.webclient.clientcredentials; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * + * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth + * + * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using credentials handled by the auth server (bael-user/bael-password) + * + * @author rozagerardo + * + */ +@PropertySource("classpath:webclient-client-credentials-oauth-application.properties") +@EnableScheduling +@SpringBootApplication +public class ClientCredentialsOauthApplication { + + public static void main(String[] args) { + SpringApplication.run(ClientCredentialsOauthApplication.class, args); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/configuration/WebClientConfig.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/configuration/WebClientConfig.java new file mode 100644 index 0000000000..8ffc92b4cd --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/configuration/WebClientConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.webclient.clientcredentials.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction; +import org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository; +import org.springframework.web.reactive.function.client.WebClient; + +@Configuration +public class WebClientConfig { + + @Bean + WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) { + ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, new UnAuthenticatedServerOAuth2AuthorizedClientRepository()); + oauth.setDefaultClientRegistrationId("bael"); + return WebClient.builder() + .filter(oauth) + .build(); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/service/WebClientChonJob.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/service/WebClientChonJob.java new file mode 100644 index 0000000000..dc38ce3f9e --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/clientcredentials/service/WebClientChonJob.java @@ -0,0 +1,33 @@ +package com.baeldung.webclient.clientcredentials.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.client.WebClient; + +@Component +public class WebClientChonJob { + + Logger logger = LoggerFactory.getLogger(WebClientChonJob.class); + + private static final String RESOURCE_URI = "http://localhost:8084/retrieve-resource"; + + @Autowired + private WebClient webClient; + + @Scheduled(fixedRate = 1000) + public void logResourceServiceResponse() { + + webClient.get() + .uri(RESOURCE_URI) + .retrieve() + .bodyToMono(String.class) + .map(string -> "We retrieved the following resource using Client Credentials Grant Type: " + string) + .subscribe(logger::info); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/ManualRequestApplication.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/ManualRequestApplication.java new file mode 100644 index 0000000000..c2762ad559 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/ManualRequestApplication.java @@ -0,0 +1,23 @@ +package com.baeldung.webclient.manualrequest; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +/** + * + * Note: This app is configured to use the authorization service and the resource service located in module spring-5-security-oauth + * + * As we usually do with other well-known auth providers (github/facebook/...) we have to log-in using user credentials (bael-user/bael-password) and client configurations (bael-client-id/bael-secret) handled by the auth server + * + * @author rozagerardo + * + */ +@SpringBootApplication +public class ManualRequestApplication { + + public static void main(String[] args) { + SpringApplication.run(ManualRequestApplication.class, args); + } + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebClientConfig.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebClientConfig.java new file mode 100644 index 0000000000..51fc60821a --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebClientConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.webclient.manualrequest.configure; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.client.WebClient; + +@Configuration +public class WebClientConfig { + + @Bean + public WebClient configureWebClient() { + return WebClient.builder() + .build(); + }; + +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebSecurityConfig.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebSecurityConfig.java new file mode 100644 index 0000000000..1753681db8 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/configure/WebSecurityConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.webclient.manualrequest.configure; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@Configuration +public class WebSecurityConfig { + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http.authorizeExchange() + .anyExchange() + .permitAll(); + return http.build(); + } +} diff --git a/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/web/ManualOauthRequestController.java b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/web/ManualOauthRequestController.java new file mode 100644 index 0000000000..9f9d6d3167 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/java/com/baeldung/webclient/manualrequest/web/ManualOauthRequestController.java @@ -0,0 +1,57 @@ +package com.baeldung.webclient.manualrequest.web; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.util.Base64Utils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import com.fasterxml.jackson.databind.JsonNode; +import com.nimbusds.oauth2.sdk.GrantType; + +import reactor.core.publisher.Mono; + +@RestController +public class ManualOauthRequestController { + + private static Logger logger = LoggerFactory.getLogger(ManualOauthRequestController.class); + + private static final String TOKEN_ENDPOINT = "localhost:8085/oauth/token"; + private static final String RESOURCE_ENDPOINT = "localhost:8084/retrieve-resource"; + private static final String CLIENT_ID = "bael-client-id"; + private static final String CLIENT_SECRET = "bael-secret"; + + @Autowired + WebClient client; + + @GetMapping("/manual-request-oauth") + public Mono obtainSecuredResource() { + logger.info("Creating web client..."); + Mono resource = client.post() + .uri(TOKEN_ENDPOINT) + .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((CLIENT_ID + ":" + CLIENT_SECRET).getBytes())) + .body(BodyInserters.fromFormData(OAuth2ParameterNames.GRANT_TYPE, GrantType.CLIENT_CREDENTIALS.getValue())) + .retrieve() + .bodyToMono(JsonNode.class) + .flatMap(tokenResponse -> { + String accessTokenValue = tokenResponse.get("access_token") + .textValue(); + logger.info("Retrieved the following access token: {}", accessTokenValue); + return client.get() + .uri(RESOURCE_ENDPOINT) + .headers(h -> h.setBearerAuth(accessTokenValue)) + .retrieve() + .bodyToMono(String.class); + }); + logger.info("non-blocking Oauth calls registered..."); + return resource.map(res -> "Retrieved the resource using a manual approach: " + res); + + } + +} diff --git a/spring-5-reactive-oauth/src/main/resources/application.yml b/spring-5-reactive-oauth/src/main/resources/application.yml index e35e19b344..bec62fdd33 100644 --- a/spring-5-reactive-oauth/src/main/resources/application.yml +++ b/spring-5-reactive-oauth/src/main/resources/application.yml @@ -1,20 +1,3 @@ -spring: - security: - oauth2: - client: - registration: - google: - client-id: YOUR_APP_CLIENT_ID - client-secret: YOUR_APP_CLIENT_SECRET - custom: - client-id: fooClientIdPassword - client-secret: secret - scopes: read,foo - authorization-grant-type: authorization_code - redirect-uri-template: http://localhost:8080/login/oauth2/code/custom - provider: - custom: - authorization-uri: http://localhost:8081/spring-security-oauth-server/oauth/authorize - token-uri: http://localhost:8081/spring-security-oauth-server/oauth/token - user-info-uri: http://localhost:8088/spring-security-oauth-resource/users/extra - user-name-attribute: user_name \ No newline at end of file +logging: + level: + root: DEBUG \ No newline at end of file diff --git a/spring-5-reactive-oauth/src/main/resources/default-application.yml b/spring-5-reactive-oauth/src/main/resources/default-application.yml new file mode 100644 index 0000000000..e35e19b344 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/resources/default-application.yml @@ -0,0 +1,20 @@ +spring: + security: + oauth2: + client: + registration: + google: + client-id: YOUR_APP_CLIENT_ID + client-secret: YOUR_APP_CLIENT_SECRET + custom: + client-id: fooClientIdPassword + client-secret: secret + scopes: read,foo + authorization-grant-type: authorization_code + redirect-uri-template: http://localhost:8080/login/oauth2/code/custom + provider: + custom: + authorization-uri: http://localhost:8081/spring-security-oauth-server/oauth/authorize + token-uri: http://localhost:8081/spring-security-oauth-server/oauth/token + user-info-uri: http://localhost:8088/spring-security-oauth-resource/users/extra + user-name-attribute: user_name \ No newline at end of file diff --git a/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-client-application.properties b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-client-application.properties new file mode 100644 index 0000000000..612777a06d --- /dev/null +++ b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-client-application.properties @@ -0,0 +1,10 @@ +spring.security.oauth2.client.registration.bael.client-name=bael +spring.security.oauth2.client.registration.bael.client-id=bael-client-id +spring.security.oauth2.client.registration.bael.client-secret=bael-secret +spring.security.oauth2.client.registration.bael.authorization-grant-type=authorization_code +spring.security.oauth2.client.registration.bael.redirect-uri=http://localhost:8080/authorize/oauth2/code/bael + +spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8085/oauth/token +spring.security.oauth2.client.provider.bael.authorization-uri=http://localhost:8085/oauth/authorize + +spring.security.user.password=pass diff --git a/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-login-application.properties b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-login-application.properties new file mode 100644 index 0000000000..edd5b80b13 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/resources/webclient-auth-code-login-application.properties @@ -0,0 +1,10 @@ +spring.security.oauth2.client.registration.bael.client-name=bael +spring.security.oauth2.client.registration.bael.client-id=bael-client-id +spring.security.oauth2.client.registration.bael.client-secret=bael-secret +spring.security.oauth2.client.registration.bael.authorization-grant-type=authorization_code +spring.security.oauth2.client.registration.bael.redirect-uri=http://localhost:8080/login/oauth2/code/bael + +spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8085/oauth/token +spring.security.oauth2.client.provider.bael.authorization-uri=http://localhost:8085/oauth/authorize +spring.security.oauth2.client.provider.bael.user-info-uri=http://localhost:8084/user +spring.security.oauth2.client.provider.bael.user-name-attribute=name diff --git a/spring-5-reactive-oauth/src/main/resources/webclient-client-credentials-oauth-application.properties b/spring-5-reactive-oauth/src/main/resources/webclient-client-credentials-oauth-application.properties new file mode 100644 index 0000000000..f82f74ec48 --- /dev/null +++ b/spring-5-reactive-oauth/src/main/resources/webclient-client-credentials-oauth-application.properties @@ -0,0 +1,4 @@ +spring.security.oauth2.client.registration.bael.authorization-grant-type=client_credentials +spring.security.oauth2.client.registration.bael.client-id=bael-client-id +spring.security.oauth2.client.registration.bael.client-secret=bael-secret +spring.security.oauth2.client.provider.bael.token-uri=http://localhost:8085/oauth/token diff --git a/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/clientcredentials/OAuth2ClientCredentialsLiveTest.java b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/clientcredentials/OAuth2ClientCredentialsLiveTest.java new file mode 100644 index 0000000000..e31815c3f8 --- /dev/null +++ b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/clientcredentials/OAuth2ClientCredentialsLiveTest.java @@ -0,0 +1,52 @@ +package com.baeldung.webclient.clientcredentials; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.webclient.clientcredentials.service.WebClientChonJob; +import com.baeldung.webclient.utils.ListAppender; + +import ch.qos.logback.classic.spi.ILoggingEvent; + +/** + * + * Note: this Live test requires the Authorization Service and the Resource service located in the spring-5-security-oauth module + * + * @author ger + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { ClientCredentialsOauthApplication.class }) +public class OAuth2ClientCredentialsLiveTest { + + @Autowired + WebClientChonJob service; + + @Before + public void clearLogList() { + ListAppender.clearEventList(); + } + + @Test + public void givenFooWithNullId_whenProcessFoo_thenLogsWithDebugTrace() throws Exception { + service.logResourceServiceResponse(); + + Thread.sleep(3000); + + Collection allLoggedEntries = ListAppender.getEvents() + .stream() + .map(ILoggingEvent::getFormattedMessage) + .collect(Collectors.toList()); + assertThat(allLoggedEntries).anyMatch(entry -> entry.contains("We retrieved the following resource using Client Credentials Grant Type: This is the resource!")); + } + +} diff --git a/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/manualrequest/OAuth2ManualRequestLiveTest.java b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/manualrequest/OAuth2ManualRequestLiveTest.java new file mode 100644 index 0000000000..94aa580f0a --- /dev/null +++ b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/manualrequest/OAuth2ManualRequestLiveTest.java @@ -0,0 +1,43 @@ +package com.baeldung.webclient.manualrequest; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +/** + * + * Note: this Live test requires not only the corresponding application running, + * but also the Authorization Service and the Resource service located in the spring-5-security-oauth module. + * + * + * @author ger + * + */ +public class OAuth2ManualRequestLiveTest { + + private static final String BASE_URL = "http://localhost:8080"; + private static final String MANUAL_REQUEST_URI = "/manual-request-oauth"; + + private static WebTestClient client; + + @Before + public void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void whenRequestingDebugHookOn_thenObtainExpectedMessage() { + ResponseSpec response = client.get() + .uri(MANUAL_REQUEST_URI) + .exchange(); + + response.expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Retrieved the resource using a manual approach: This is the resource!"); + } + +} diff --git a/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/utils/ListAppender.java b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/utils/ListAppender.java new file mode 100644 index 0000000000..6f8fbe004a --- /dev/null +++ b/spring-5-reactive-oauth/src/test/java/com/baeldung/webclient/utils/ListAppender.java @@ -0,0 +1,25 @@ +package com.baeldung.webclient.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(); + } +} \ No newline at end of file diff --git a/spring-5-reactive-oauth/src/test/resources/logback-test.xml b/spring-5-reactive-oauth/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..891c54bfd3 --- /dev/null +++ b/spring-5-reactive-oauth/src/test/resources/logback-test.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index fc898a56dc..c39bb616f8 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -17,4 +17,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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) +- [Debugging Reactive Streams in Spring 5](https://www.baeldung.com/spring-debugging-reactive-streams) diff --git a/spring-5-security-oauth/README.md b/spring-5-security-oauth/README.md index f13925992b..5a444d4784 100644 --- a/spring-5-security-oauth/README.md +++ b/spring-5-security-oauth/README.md @@ -2,3 +2,4 @@ - [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) +- [Customizing Authorization and Token Requests with Spring Security 5.1 Client](https://www.baeldung.com/spring-security-custom-oauth-requests) diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java index 557c23b368..1478b03d2e 100644 --- a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/SpringOAuthApplication.java @@ -2,7 +2,9 @@ package com.baeldung.oauth2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; +@PropertySource("classpath:default-application.properties") @SpringBootApplication public class SpringOAuthApplication { diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java index 6ab4d525bf..174e5b0fdf 100644 --- a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java @@ -3,10 +3,12 @@ package com.baeldung.oauth2extractors; import org.apache.logging.log4j.util.Strings; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.AbstractEnvironment; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +@PropertySource("classpath:default-application.properties") @SpringBootApplication @Controller public class ExtractorsApplication { diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/AuthorizationServerApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/AuthorizationServerApplication.java new file mode 100644 index 0000000000..d72704386c --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/AuthorizationServerApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.webclient.authorizationserver; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; + +@EnableAuthorizationServer +@PropertySource("classpath:webclient-authorization-application.properties") +@SpringBootApplication +public class AuthorizationServerApplication { + + public static void main(String[] args) { + SpringApplication.run(AuthorizationServerApplication.class, args); + } + +} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/configuration/WebSecurityConfig.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/configuration/WebSecurityConfig.java new file mode 100644 index 0000000000..5dd15f1b8c --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/authorizationserver/configuration/WebSecurityConfig.java @@ -0,0 +1,26 @@ +package com.baeldung.webclient.authorizationserver.configuration; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@EnableWebSecurity +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/login", "/user") + .permitAll() + .and() + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .formLogin() + .and() + .httpBasic(); + } +} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/ResourceServerApplication.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/ResourceServerApplication.java new file mode 100644 index 0000000000..50ad293ef8 --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/ResourceServerApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.webclient.resourceserver; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; + +@EnableResourceServer +@PropertySource("webclient-resources-application.properties") +@SpringBootApplication +public class ResourceServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ResourceServerApplication.class, args); + } + +} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/configuration/AuthorizationConfigs.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/configuration/AuthorizationConfigs.java new file mode 100644 index 0000000000..5aea1983db --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/configuration/AuthorizationConfigs.java @@ -0,0 +1,29 @@ +package com.baeldung.webclient.resourceserver.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.provider.token.RemoteTokenServices; +import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; + +@Configuration +public class AuthorizationConfigs { + + @Value("${oauth.authserver.client-id}") + String clientId; + + @Value("${oauth.authserver.client-secret}") + String clientSecret; + + @Value("${oauth.authserver.check-token-endpoint}") + String checkTokenEndpoint; + + @Bean + public ResourceServerTokenServices tokenSvc() { + RemoteTokenServices remoteService = new RemoteTokenServices(); + remoteService.setCheckTokenEndpointUrl(checkTokenEndpoint); + remoteService.setClientId(clientId); + remoteService.setClientSecret(clientSecret); + return remoteService; + } +} diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/web/ResourceRestController.java b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/web/ResourceRestController.java new file mode 100644 index 0000000000..aef0fb4d7d --- /dev/null +++ b/spring-5-security-oauth/src/main/java/com/baeldung/webclient/resourceserver/web/ResourceRestController.java @@ -0,0 +1,23 @@ +package com.baeldung.webclient.resourceserver.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ResourceRestController { + + @GetMapping("/retrieve-resource") + public String retrieveResource() { + return "This is the resource!"; + } + + @GetMapping("/user") + @ResponseBody + public Principal user(Principal user) { + return user; + } + +} diff --git a/spring-5-security-oauth/src/main/resources/application.properties b/spring-5-security-oauth/src/main/resources/application.properties index 5912b0f755..c84e745918 100644 --- a/spring-5-security-oauth/src/main/resources/application.properties +++ b/spring-5-security-oauth/src/main/resources/application.properties @@ -1,5 +1,3 @@ -server.port=8081 - logging.level.root=INFO logging.level.com.baeldung.dsl.ClientErrorLoggingFilter=DEBUG \ No newline at end of file diff --git a/spring-5-security-oauth/src/main/resources/default-application.properties b/spring-5-security-oauth/src/main/resources/default-application.properties new file mode 100644 index 0000000000..bafddced85 --- /dev/null +++ b/spring-5-security-oauth/src/main/resources/default-application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/spring-5-security-oauth/src/main/resources/webclient-authorization-application.properties b/spring-5-security-oauth/src/main/resources/webclient-authorization-application.properties new file mode 100644 index 0000000000..9531045359 --- /dev/null +++ b/spring-5-security-oauth/src/main/resources/webclient-authorization-application.properties @@ -0,0 +1,13 @@ +server.port=8085 + +security.oauth2.client.client-id=bael-client-id +security.oauth2.client.client-secret=bael-secret +security.oauth2.client.scope=read,write + +security.oauth2.authorization.check-token-access=isAuthenticated() + +spring.security.user.name=bael-user +spring.security.user.password=bael-password + +security.oauth2.client.registered-redirect-uri=http://localhost:8080/login/oauth2/code/bael, http://localhost:8080/authorize/oauth2/code/bael +security.oauth2.client.use-current-uri=false \ No newline at end of file diff --git a/spring-5-security-oauth/src/main/resources/webclient-resources-application.properties b/spring-5-security-oauth/src/main/resources/webclient-resources-application.properties new file mode 100644 index 0000000000..1cfb9ca12d --- /dev/null +++ b/spring-5-security-oauth/src/main/resources/webclient-resources-application.properties @@ -0,0 +1,6 @@ +server.port=8084 + +#spring.security.oauth2.resourceserver.jwt.issuer-uri=localhost:8085 +oauth.authserver.client-id=bael-client-id +oauth.authserver.client-secret=bael-secret +oauth.authserver.check-token-endpoint=http://localhost:8085/oauth/check_token diff --git a/spring-amqp-simple/pom.xml b/spring-amqp-simple/pom.xml index 57d84acee6..45cdc066a0 100644 --- a/spring-amqp-simple/pom.xml +++ b/spring-amqp-simple/pom.xml @@ -8,10 +8,10 @@ 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-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 7cafc5aa24..0ffc1820b8 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -57,6 +57,27 @@ + + beanstalk + + ${project.name}-eb + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/cloud/config/*.java + + + + + + openshift diff --git a/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties b/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties new file mode 100644 index 0000000000..de03a3b5bb --- /dev/null +++ b/spring-boot-bootstrap/src/main/resources/application-beanstalk.properties @@ -0,0 +1,3 @@ +spring.datasource.url=jdbc:mysql://${rds.hostname}:${rds.port}/${rds.db.name} +spring.datasource.username=${rds.username} +spring.datasource.password=${rds.password} \ No newline at end of file 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/spring-boot-libraries/mvnw b/spring-boot-libraries/mvnw new file mode 100644 index 0000000000..e96ccd5fbb --- /dev/null +++ b/spring-boot-libraries/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-libraries/mvnw.cmd b/spring-boot-libraries/mvnw.cmd new file mode 100644 index 0000000000..6a6eec39ba --- /dev/null +++ b/spring-boot-libraries/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-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-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java similarity index 100% rename from spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java rename to spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java diff --git a/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java similarity index 100% rename from spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java rename to spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md index c125c96c36..553b02ebf0 100644 --- a/spring-boot-ops/README.md +++ b/spring-boot-ops/README.md @@ -9,4 +9,4 @@ - [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) - [Spring Boot Console Application](http://www.baeldung.com/spring-boot-console-app) - [Comparing Embedded Servlet Containers in Spring Boot](http://www.baeldung.com/spring-boot-servlet-containers) - + - [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app) diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md new file mode 100644 index 0000000000..0a8d13cf76 --- /dev/null +++ b/spring-boot-rest/README.md @@ -0,0 +1,3 @@ +Module for the articles that are part of the Spring REST E-book: + +1. [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml new file mode 100644 index 0000000000..baf9d35a09 --- /dev/null +++ b/spring-boot-rest/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + com.baeldung.web + spring-boot-rest + spring-boot-rest + Spring Boot Rest Module + war + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + com.baeldung.SpringBootRestApplication + + diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/SpringBootRestApplication.java b/spring-boot-rest/src/main/java/com/baeldung/web/SpringBootRestApplication.java new file mode 100644 index 0000000000..62aae7619d --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/SpringBootRestApplication.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootRestApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootRestApplication.class, args); + } + +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/config/WebConfig.java b/spring-boot-rest/src/main/java/com/baeldung/web/config/WebConfig.java new file mode 100644 index 0000000000..808e946218 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/config/WebConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.web.config; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebConfig { + +} \ No newline at end of file diff --git a/spring-boot-rest/src/main/resources/application.properties b/spring-boot-rest/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/SpringContextIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..0c1fdf372b --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.boot.rest; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} 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/README.MD b/spring-boot-testing/README.MD index a609b5bf09..144c3581f7 100644 --- a/spring-boot-testing/README.MD +++ b/spring-boot-testing/README.MD @@ -4,3 +4,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) +- [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) diff --git a/spring-boot-testing/pom.xml b/spring-boot-testing/pom.xml index 2a498e54c5..c2c886a4fe 100644 --- a/spring-boot-testing/pom.xml +++ b/spring-boot-testing/pom.xml @@ -23,6 +23,10 @@ org.springframework.boot spring-boot-starter-tomcat + + org.springframework.boot + spring-boot-starter-security + org.springframework.boot spring-boot-starter-test @@ -43,6 +47,13 @@ ${spock.version} test + + + io.rest-assured + rest-assured + test + + @@ -98,51 +109,14 @@ - + - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - org.baeldung.boot.Application + com.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 index c1b6558b26..cb0d0c1532 100644 --- a/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.boot; +package com.baeldung.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java b/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java new file mode 100644 index 0000000000..595c34254b --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.boot.controller.rest; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HomeController { + + @GetMapping("/") + public String salutation() { + return "Welcome !"; + } + +} \ No newline at end of file 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 index 5b65599e00..7247ca3dfa 100644 --- 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 @@ -1,4 +1,6 @@ -package org.baeldung.boot.controller.rest; +package com.baeldung.boot.controller.rest; + +import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; @@ -9,8 +11,6 @@ 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 { diff --git a/spring-boot-testing/src/main/resources/application-test.properties b/spring-boot-testing/src/main/resources/application-test.properties new file mode 100644 index 0000000000..8d5e86ba26 --- /dev/null +++ b/spring-boot-testing/src/main/resources/application-test.properties @@ -0,0 +1,3 @@ + +# test properties +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration \ No newline at end of file diff --git a/spring-boot-testing/src/main/resources/application.properties b/spring-boot-testing/src/main/resources/application.properties new file mode 100644 index 0000000000..e378aacdd5 --- /dev/null +++ b/spring-boot-testing/src/main/resources/application.properties @@ -0,0 +1,4 @@ + +# security +spring.security.user.name=john +spring.security.user.password=123 \ 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/com/baeldung/boot/LoadContextTest.groovy similarity index 87% rename from spring-boot-testing/src/test/groovy/org/baeldung/boot/LoadContextTest.groovy rename to spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy index 2d4a7ca2cf..85b0a4b89b 100644 --- a/spring-boot-testing/src/test/groovy/org/baeldung/boot/LoadContextTest.groovy +++ b/spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy @@ -1,6 +1,6 @@ -package org.baeldung.boot +package com.baeldung.boot -import org.baeldung.boot.controller.rest.WebController +import com.baeldung.boot.controller.rest.WebController import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import spock.lang.Narrative diff --git a/spring-boot-testing/src/test/groovy/org/baeldung/boot/WebControllerTest.groovy b/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy similarity index 96% rename from spring-boot-testing/src/test/groovy/org/baeldung/boot/WebControllerTest.groovy rename to spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy index fe1b34ab8c..d8b4e03adc 100644 --- a/spring-boot-testing/src/test/groovy/org/baeldung/boot/WebControllerTest.groovy +++ b/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy @@ -1,4 +1,4 @@ -package org.baeldung.boot +package com.baeldung.boot import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc @@ -12,8 +12,8 @@ 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 +@AutoConfigureMockMvc(secure=false) +@WebMvcTest() class WebControllerTest extends Specification { @Autowired diff --git a/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias b/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias new file mode 100644 index 0000000000..f2fc2f48e2 Binary files /dev/null and b/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias differ diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java new file mode 100644 index 0000000000..a4a29cddf3 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.autoconfig.exclude; + +import static org.junit.Assert.assertEquals; +import io.restassured.RestAssured; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration") +public class ExcludeAutoConfig1IntegrationTest { + + @Test + public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { + int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java new file mode 100644 index 0000000000..cdf79b159c --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.autoconfig.exclude; + +import static org.junit.Assert.assertEquals; +import io.restassured.RestAssured; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@ActiveProfiles("test") +public class ExcludeAutoConfig2IntegrationTest { + + @Test + public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { + int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java new file mode 100644 index 0000000000..0e45d1e9e5 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.autoconfig.exclude; + +import static org.junit.Assert.assertEquals; +import io.restassured.RestAssured; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) +public class ExcludeAutoConfig3IntegrationTest { + + @Test + public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { + int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java new file mode 100644 index 0000000000..8429aed6cd --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.autoconfig.exclude; + +import static org.junit.Assert.assertEquals; +import io.restassured.RestAssured; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) +public class ExcludeAutoConfig4IntegrationTest { + + @Test + public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { + int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java new file mode 100644 index 0000000000..7c162f85ab --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.autoconfig.exclude; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(scanBasePackages="com.baeldung.boot", exclude=SecurityAutoConfiguration.class) +public class TestApplication { + + public static void main(String[] args) { + SpringApplication.run(TestApplication.class, args); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..63ab07fdb7 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.boot; + +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 whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java new file mode 100644 index 0000000000..fe71f44ddf --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.boot.autoconfig; + +import static org.junit.Assert.assertEquals; +import io.restassured.RestAssured; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +public class AutoConfigIntegrationTest { + + @Test + public void givenNoAuthentication_whenAccessHome_thenUnauthorized() { + int statusCode = RestAssured.get("http://localhost:8080/").statusCode(); + assertEquals(HttpStatus.UNAUTHORIZED.value(), statusCode); + } + + @Test + public void givenAuthentication_whenAccessHome_thenOK() { + int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:8080/").statusCode(); + assertEquals(HttpStatus.OK.value(), statusCode); + } +} diff --git a/spring-boot/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/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/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-cloud/spring-cloud-kubernetes/README.md b/spring-cloud/spring-cloud-kubernetes/README.md index 295ead1c2f..2387758626 100644 --- a/spring-cloud/spring-cloud-kubernetes/README.md +++ b/spring-cloud/spring-cloud-kubernetes/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Running Spring Boot Applications With Minikube](https://www.baeldung.com/spring-boot-minikube) +- [Self-Healing Applications with Kubernetes and Spring Boot](https://www.baeldung.com/spring-boot-kubernetes-self-healing-apps) 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/main/java/com/baeldung/annotation/MyBean.java b/spring-core/src/main/java/com/baeldung/annotation/MyBean.java new file mode 100644 index 0000000000..9a1fd3beec --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotation/MyBean.java @@ -0,0 +1,26 @@ +package com.baeldung.annotation; + +import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@Component +public class MyBean { + + private final TestBean testBean; + + public MyBean(TestBean testBean) { + this.testBean = testBean; + System.out.println("Hello from constructor"); + } + + @PostConstruct + private void postConstruct() { + System.out.println("Hello from @PostConstruct method"); + } + + @PreDestroy + public void preDestroy() { + System.out.println("Bean is being destroyed"); + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/annotation/TestBean.java b/spring-core/src/main/java/com/baeldung/annotation/TestBean.java new file mode 100644 index 0000000000..0539e10751 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotation/TestBean.java @@ -0,0 +1,8 @@ +package com.baeldung.annotation; + +import org.springframework.stereotype.Component; + +@Component +public class TestBean { + +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/value/ValuesApp.java b/spring-core/src/main/java/com/baeldung/value/ValuesApp.java index f525dfde89..80893c1adf 100644 --- a/spring-core/src/main/java/com/baeldung/value/ValuesApp.java +++ b/spring-core/src/main/java/com/baeldung/value/ValuesApp.java @@ -2,6 +2,7 @@ package com.baeldung.value; import java.util.Arrays; import java.util.List; +import java.util.Map; import javax.annotation.PostConstruct; @@ -45,6 +46,27 @@ public class ValuesApp { @Value("#{'${listOfValues}'.split(',')}") private List valuesList; + + @Value("#{${valuesMap}}") + private Map valuesMap; + + @Value("#{${valuesMap}.key1}") + private Integer valuesMapKey1; + + @Value("#{${valuesMap}['unknownKey']}") + private Integer unknownMapKey; + + @Value("#{${unknownMap : {key1:'1', key2 : '2'}}}") + private Map unknownMap; + + @Value("#{${valuesMap}['unknownKey'] ?: 5}") + private Integer unknownMapKeyWithDefaultValue; + + @Value("#{${valuesMap}.?[value>'1']}") + private Map valuesMapFiltered; + + @Value("#{systemProperties}") + private Map systemPropertiesMap; public static void main(String[] args) { System.setProperty("systemValue", "Some system parameter value"); @@ -69,5 +91,12 @@ public class ValuesApp { System.out.println(spelSomeDefault); System.out.println(someBeanValue); System.out.println(valuesList); + System.out.println(valuesMap); + System.out.println(valuesMapKey1); + System.out.println(unknownMapKey); + System.out.println(unknownMap); + System.out.println(unknownMapKeyWithDefaultValue); + System.out.println(valuesMapFiltered); + System.out.println(systemPropertiesMap); } } diff --git a/spring-core/src/main/resources/values.properties b/spring-core/src/main/resources/values.properties index d7d61b8ee8..c6db5873fb 100644 --- a/spring-core/src/main/resources/values.properties +++ b/spring-core/src/main/resources/values.properties @@ -1,3 +1,4 @@ value.from.file=Value got from the file priority=Properties file -listOfValues=A,B,C \ No newline at end of file +listOfValues=A,B,C +valuesMap={key1:'1', key2 : '2', key3 : '3'} \ 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-ehcache/.gitignore b/spring-ehcache/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-ehcache/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-ehcache/README.md b/spring-ehcache/README.md new file mode 100644 index 0000000000..749441375e --- /dev/null +++ b/spring-ehcache/README.md @@ -0,0 +1,7 @@ +## Spring Ehcache Example Project + +A simple example of using ehcache with spring-boot. + +### Relevant Articles: +- [Spring Boot Ehcache Example](http://www.baeldung.com/spring-ehcache) + diff --git a/spring-ehcache/checkstyle.xml b/spring-ehcache/checkstyle.xml new file mode 100644 index 0000000000..85063a7570 --- /dev/null +++ b/spring-ehcache/checkstyle.xml @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/spring-ehcache/pom.xml b/spring-ehcache/pom.xml new file mode 100644 index 0000000000..b8378617c5 --- /dev/null +++ b/spring-ehcache/pom.xml @@ -0,0 +1,87 @@ + + 4.0.0 + spring-ehcache + 0.1-SNAPSHOT + spring-ehcache + jar + + + 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-cache + + + javax.cache + cache-api + + + org.ehcache + ehcache + + + + + spring-ehcache + + + src/main/resources + true + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + + check + + + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + + + + + 3.0.0 + false + + + diff --git a/spring-ehcache/src/main/java/com/baeldung/cachetest/Application.java b/spring-ehcache/src/main/java/com/baeldung/cachetest/Application.java new file mode 100644 index 0000000000..a1ce7a5317 --- /dev/null +++ b/spring-ehcache/src/main/java/com/baeldung/cachetest/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.cachetest; + +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-ehcache/src/main/java/com/baeldung/cachetest/config/CacheConfig.java b/spring-ehcache/src/main/java/com/baeldung/cachetest/config/CacheConfig.java new file mode 100644 index 0000000000..3cf2309cb9 --- /dev/null +++ b/spring-ehcache/src/main/java/com/baeldung/cachetest/config/CacheConfig.java @@ -0,0 +1,57 @@ +package com.baeldung.cachetest.config; + +import java.math.BigDecimal; +import java.time.Duration; + +import javax.cache.CacheManager; + +import org.ehcache.config.CacheConfiguration; +import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheEventListenerConfigurationBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; +import org.ehcache.config.units.EntryUnit; +import org.ehcache.config.units.MemoryUnit; +import org.ehcache.event.EventType; +import org.ehcache.jsr107.Eh107Configuration; +import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableCaching +public class CacheConfig { + + private static final int ON_HEAP_CACHE_SIZE_ENTRIES = 2; + private static final int OFF_HEAP_CACHE_SIZE_MB = 10; + private static final int CACHE_EXPIRY_SECONDS = 30; + + @Bean + public JCacheManagerCustomizer jcacheManagerCustomizer() { + return new JCacheManagerCustomizer() { + + @Override + public void customize(CacheManager cacheManager) { + ResourcePools resourcePools = ResourcePoolsBuilder.newResourcePoolsBuilder() + .heap(ON_HEAP_CACHE_SIZE_ENTRIES, EntryUnit.ENTRIES) + .offheap(OFF_HEAP_CACHE_SIZE_MB, MemoryUnit.MB).build(); + + CacheEventListenerConfigurationBuilder eventLoggerConfig = CacheEventListenerConfigurationBuilder + .newEventListenerConfiguration(new CacheEventLogger(), EventType.CREATED, EventType.EXPIRED) + .unordered().asynchronous(); + + CacheConfiguration cacheConfiguration = CacheConfigurationBuilder + .newCacheConfigurationBuilder(Long.class, BigDecimal.class, resourcePools) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(CACHE_EXPIRY_SECONDS))) + .add(eventLoggerConfig).build(); + + cacheManager.createCache("squareCache", + Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfiguration)); + + } + }; + } + +} diff --git a/spring-ehcache/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java b/spring-ehcache/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java new file mode 100644 index 0000000000..c8ead85f1e --- /dev/null +++ b/spring-ehcache/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java @@ -0,0 +1,18 @@ +package com.baeldung.cachetest.config; + +import org.ehcache.event.CacheEvent; +import org.ehcache.event.CacheEventListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CacheEventLogger implements CacheEventListener { + + private static final Logger log = LoggerFactory.getLogger(CacheEventLogger.class); + + @Override + public void onEvent(CacheEvent cacheEvent) { + log.info("Cache event {} for item with key {}. Old value = {}, New value = {}", cacheEvent.getType(), + cacheEvent.getKey(), cacheEvent.getOldValue(), cacheEvent.getNewValue()); + } + +} diff --git a/spring-ehcache/src/main/java/com/baeldung/cachetest/rest/NumberController.java b/spring-ehcache/src/main/java/com/baeldung/cachetest/rest/NumberController.java new file mode 100644 index 0000000000..4115c34cc4 --- /dev/null +++ b/spring-ehcache/src/main/java/com/baeldung/cachetest/rest/NumberController.java @@ -0,0 +1,29 @@ +package com.baeldung.cachetest.rest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +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 com.baeldung.cachetest.service.NumberService; + +@RestController +@RequestMapping(path = "/number", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) +public class NumberController { + + private final static Logger log = LoggerFactory.getLogger(NumberController.class); + + @Autowired + private NumberService numberService; + + @GetMapping(path = "/square/{number}") + public String getThing(@PathVariable Long number) { + log.info("call numberService to square {}", number); + return String.format("{\"square\": %s}", numberService.square(number)); + } + +} diff --git a/spring-ehcache/src/main/java/com/baeldung/cachetest/service/NumberService.java b/spring-ehcache/src/main/java/com/baeldung/cachetest/service/NumberService.java new file mode 100644 index 0000000000..bcd930f5e1 --- /dev/null +++ b/spring-ehcache/src/main/java/com/baeldung/cachetest/service/NumberService.java @@ -0,0 +1,22 @@ +package com.baeldung.cachetest.service; + +import java.math.BigDecimal; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +@Service +public class NumberService { + + private final static Logger log = LoggerFactory.getLogger(NumberService.class); + + @Cacheable(value = "squareCache", key = "#number", condition = "#number>10") + public BigDecimal square(Long number) { + BigDecimal square = BigDecimal.valueOf(number).multiply(BigDecimal.valueOf(number)); + log.info("square of {} is {}", number, square); + return square; + } + +} diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 5e7b50d291..b548de3701 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -101,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 bbd6025418..8bce500a86 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -5,10 +5,10 @@ spring-jooq - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -129,6 +129,9 @@ com.baeldung.jooq.introduction.db src/main/java + + + @@ -185,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..b76d4f10c0 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.2.2.RELEASE + 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..b313eafdb9 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 @@ -13,8 +13,11 @@ import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.annotation.TopicPartition; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.kafka.support.SendResult; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.ListenableFutureCallback; @SpringBootApplication public class KafkaApplication { @@ -22,7 +25,7 @@ public class KafkaApplication { public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(KafkaApplication.class, args); - + MessageProducer producer = context.getBean(MessageProducer.class); MessageListener listener = context.getBean(MessageListener.class); /* @@ -98,11 +101,24 @@ public class KafkaApplication { private String greetingTopicName; public void sendMessage(String message) { - kafkaTemplate.send(topicName, message); + + ListenableFuture> future = kafkaTemplate.send(topicName, message); + + future.addCallback(new ListenableFutureCallback>() { + + @Override + public void onSuccess(SendResult result) { + System.out.println("Sent message=[" + message + "] with offset=[" + result.getRecordMetadata().offset() + "]"); + } + @Override + public void onFailure(Throwable ex) { + System.out.println("Unable to send message=[" + message + "] due to : " + ex.getMessage()); + } + }); } 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 +140,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/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java new file mode 100644 index 0000000000..a3426e78a3 --- /dev/null +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaTopicConfig.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.kafka; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.KafkaAdmin; + +@Configuration +public class KafkaTopicConfig { + + @Value(value = "${kafka.bootstrapAddress}") + private String bootstrapAddress; + + @Value(value = "${message.topic.name}") + private String topicName; + + @Value(value = "${partitioned.topic.name}") + private String partionedTopicName; + + @Value(value = "${filtered.topic.name}") + private String filteredTopicName; + + @Value(value = "${greeting.topic.name}") + private String greetingTopicName; + + @Bean + public KafkaAdmin kafkaAdmin() { + Map configs = new HashMap<>(); + configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); + return new KafkaAdmin(configs); + } + + @Bean + public NewTopic topic1() { + return new NewTopic(topicName, 1, (short) 1); + } + + @Bean + public NewTopic topic2() { + return new NewTopic(partionedTopicName, 6, (short) 1); + } + + @Bean + public NewTopic topic3() { + return new NewTopic(filteredTopicName, 1, (short) 1); + } + + @Bean + public NewTopic topic4() { + return new NewTopic(greetingTopicName, 1, (short) 1); + } +} diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java similarity index 90% rename from spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java index 40bf86c76f..d8fb3131f5 100644 --- a/spring-kafka/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-kafka/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -9,7 +9,7 @@ import com.baeldung.spring.kafka.KafkaApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = KafkaApplication.class) -public class SpringContextIntegrationTest { +public class SpringContextLiveTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java b/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java new file mode 100644 index 0000000000..b8195633fd --- /dev/null +++ b/spring-kafka/src/test/java/org/baeldung/SpringContextManualTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.kafka.KafkaApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KafkaApplication.class) +public class SpringContextManualTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-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-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-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 8d7ad0fa7f..65fa4339d6 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -196,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-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-reactor/pom.xml b/spring-reactor/pom.xml index e828c44f74..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,7 +27,12 @@ io.projectreactor reactor-bus + 2.0.8.RELEASE + + + io.projectreactor + reactor-core + 2.0.8.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 e63d0ee22e..8c30e76296 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -6,11 +6,13 @@ 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-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/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-rest/README.md b/spring-rest/README.md index efa0dbab60..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) diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index a1a1beb4f4..12520a0d01 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -202,7 +202,7 @@ 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-rest/README.md b/spring-security-rest/README.md index c396948a59..f71eead9ae 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -15,5 +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) -- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) - [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-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-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-sleuth/pom.xml b/spring-sleuth/pom.xml index dd4477c551..c693466ab0 100644 --- a/spring-sleuth/pom.xml +++ b/spring-sleuth/pom.xml @@ -9,10 +9,10 @@ spring-sleuth - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 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-vertx/pom.xml b/spring-vertx/pom.xml index 14ed77d359..7a0bdc81d0 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -8,10 +8,10 @@ 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-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/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/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/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/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/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 121609ad4d..b0e1c7e8d9 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -138,7 +138,7 @@ - 2.8.5 + 2.9.7 2.9.6