diff --git a/algorithms/README.md b/algorithms/README.md index 23209a5966..df445146d9 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -20,3 +20,4 @@ - [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze) - [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku) - [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words) +- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations) diff --git a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 6ab7dbb4e5..c82883425d 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -6,6 +6,7 @@ import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.slope_one.SlopeOne; +import com.baeldung.algorithms.pairsaddupnumber.FindPairs; public class RunAlgorithm { @@ -17,6 +18,7 @@ public class RunAlgorithm { System.out.println("3 - Simple Genetic Algorithm"); System.out.println("4 - Ant Colony"); System.out.println("5 - Dijkstra"); + System.out.println("6 - All pairs in an array that add up to a given sum"); int decision = in.nextInt(); switch (decision) { case 1: @@ -37,6 +39,12 @@ public class RunAlgorithm { case 5: System.out.println("Please run the DijkstraAlgorithmTest."); break; + case 6: + final FindPairs findPairs = new FindPairs(); + final int[] input = {1, 4, 3, 2, 1, 4, 4, 3, 3}; + final int sum = 6; + findPairs.execute(input, sum); + break; default: System.out.println("Unknown option"); break; diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java new file mode 100644 index 0000000000..e86e1d5a22 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java @@ -0,0 +1,72 @@ +package com.baeldung.algorithms.pairsaddupnumber; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + +/** + * Find all different pairs of numbers in an array that add up to a given sum - Complexity O(n) + */ +public class DifferentPairs { + + /** + * Show all different pairs using traditional "for" loop + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithForLoop(int[] input, int sum) { + final List allDifferentPairs = new ArrayList<>(); + // Aux. hash map + final Map pairs = new HashMap(); + for (int i : input) { + if (pairs.containsKey(i)) { + if (pairs.get(i) != null) { + // Add pair to returned list + allDifferentPairs.add(i); + } + // Mark pair as added to prevent duplicates + pairs.put(sum - i, null); + } else if (!pairs.containsValue(i)) { + // Add pair to aux. hash map + pairs.put(sum - i, i); + } + } + return allDifferentPairs; + } + + /** + * Show all different pairs using Java 8 stream API + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithStreamApi(int[] input, int sum) { + final List allDifferentPairs = new ArrayList<>(); + // Aux. hash map + final Map pairs = new HashMap(); + IntStream.range(0, input.length).forEach(i -> { + if (pairs.containsKey(input[i])) { + if (pairs.get(input[i]) != null) { + // Add pair to returned list + allDifferentPairs.add(input[i]); + } + // Mark pair as added to prevent duplicates + pairs.put(sum - input[i], null); + } else if (!pairs.containsValue(input[i])) { + // Add pair to aux. hash map + pairs.put(sum - input[i], input[i]); + } + } + ); + return allDifferentPairs; + } +} + diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java new file mode 100644 index 0000000000..6b10c73bcf --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java @@ -0,0 +1,51 @@ +package com.baeldung.algorithms.pairsaddupnumber; + + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +/** + * Find all existing pairs of numbers in an array that add up to a given sum - Complexity O(n^2) "Brute force" + */ +public class ExistingPairs { + + /** + * Show all existing pairs using traditional "for" loop + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithForLoop(int[] input, int sum) { + final List allExistingPairs = new ArrayList<>(); + for (int i = 0; i < input.length; i++) { + for (int j = 0; j < input.length; j++) { + if (j != i && (input[i] + input[j]) == sum) { + allExistingPairs.add(input[i]); + } + } + } + return allExistingPairs; + } + + /** + * Show all existing pairs using Java 8 stream API + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithStreamApi(int[] input, int sum) { + final List allExistingPairs = new ArrayList<>(); + IntStream.range(0, input.length).forEach(i -> + IntStream.range(0, input.length) + .filter(j -> i != j && input[i] + input[j] == sum) + .forEach(j -> allExistingPairs.add(input[i])) + ); + return allExistingPairs; + } +} + diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java new file mode 100644 index 0000000000..4b309332ae --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java @@ -0,0 +1,74 @@ +package com.baeldung.algorithms.pairsaddupnumber; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + + +public class FindPairs { + + public void execute(int[] input, int sum) { + final StringBuilder inputArray = new StringBuilder(); + inputArray.append("{"); + IntStream.range(0, input.length).forEach(i -> inputArray.append(input[i] + ", ")); + inputArray.append("}"); + System.out.println(" Given number array: " + inputArray.toString()); + System.out.println(" Given sum: " + sum); + /* Call services */ + getDifferentPairs(input, sum); + getExistingPairs(input, sum); + } + + /** + * Print all existing pairs for the given inputs: input array & sum number + */ + private static void getExistingPairs(int[] input, int sum) { + List pairs = new ArrayList<>(); + System.out.println("~ All existing pairs ~"); + + /* Traditional FOR loop */ + // Call method + pairs = ExistingPairs.findPairsWithForLoop(input, sum); + // Create a pretty printing + final StringBuilder output1 = new StringBuilder(); + pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2)); + + /* Java 8 stream API */ + // Call the method + pairs = ExistingPairs.findPairsWithStreamApi(input, sum); + // Create a pretty printing + final StringBuilder output2 = new StringBuilder(); + pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2)); + } + + /** + * Print all different pairs for the given inputs: input array & sum number + */ + private static void getDifferentPairs(int[] input, int sum) { + List pairs = new ArrayList<>(); + System.out.println("~ All different pairs ~"); + + /* Traditional FOR loop */ + // Call method + pairs = DifferentPairs.findPairsWithForLoop(input, sum); + // Create a pretty printing + final StringBuilder output3 = new StringBuilder(); + pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2)); + + /* Java 8 stream API */ + // Call method + pairs = DifferentPairs.findPairsWithStreamApi(input, sum); + // Create a pretty printing + final StringBuilder output4 = new StringBuilder(); + pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2)); + } +} + diff --git a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java new file mode 100644 index 0000000000..48fcfb871c --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.algorithms.pairsaddupnumber; + +import org.junit.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class DifferentPairsUnitTest { + + /* All different pairs */ + + @Test + public void whenTraditionalLoop_thenReturnAllDifferentPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = DifferentPairs.findPairsWithForLoop(input, sum); + /* Check results */ + assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8); + } + + @Test + public void whenStreamApi_thenReturnAllDifferentPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = DifferentPairs.findPairsWithStreamApi(input, sum); + /* Check results */ + assertNotNull(pairs); + assertEquals(pairs.size(),2); + assertEquals(pairs.get(0), new Integer(4)); + assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java new file mode 100644 index 0000000000..ac6d6cc885 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.pairsaddupnumber; + +import org.junit.Test; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class ExistingPairsUnitTest { + + /* All existing pairs */ + + @Test + public void whenTraditionalLoop_thenReturnAllExistingPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = ExistingPairs.findPairsWithForLoop(input, sum); + /* Check results */ + assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8); + } + + @Test + public void whenStreamApi_thenReturnAllExistingPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = ExistingPairs.findPairsWithStreamApi(input, sum); + /* Check results */ + assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8); + } +} diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml index f7439dc244..c9522e2b75 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -82,42 +82,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - - json - - - - - - - - 1.1 4.3 diff --git a/apache-poi/README.md b/apache-poi/README.md index c052bc9bf6..862981991d 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -1,4 +1,4 @@ ### Relevant Articles: - [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi) - [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel) -- [Creating a MS PowerPoint Presentation in Java](https://github.com/eugenp/tutorials/tree/master/apache-poi) +- [Creating a MS PowerPoint Presentation in Java](http://www.baeldung.com/apache-poi-slideshow) diff --git a/aws/src/main/java/com/baeldung/sqs/SQSApplication.java b/aws/src/main/java/com/baeldung/sqs/SQSApplication.java new file mode 100644 index 0000000000..978506a24f --- /dev/null +++ b/aws/src/main/java/com/baeldung/sqs/SQSApplication.java @@ -0,0 +1,146 @@ +package com.baeldung.sqs; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.sqs.AmazonSQSClientBuilder; +import com.amazonaws.services.sqs.model.CreateQueueRequest; +import com.amazonaws.services.sqs.model.DeleteMessageRequest; +import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; +import com.amazonaws.services.sqs.model.GetQueueAttributesResult; +import com.amazonaws.services.sqs.model.MessageAttributeValue; +import com.amazonaws.services.sqs.model.ReceiveMessageRequest; +import com.amazonaws.services.sqs.model.SendMessageBatchRequest; +import com.amazonaws.services.sqs.model.SendMessageRequest; +import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; +import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry; +import com.amazonaws.services.sqs.model.Message; +import com.amazonaws.services.sqs.AmazonSQS; + +public class SQSApplication { + + private static final AWSCredentials credentials; + + static { + // put your accesskey and secretkey here + credentials = new BasicAWSCredentials( + "", + "" + ); + } + + public static void main(String[] args) { + + // Set up the client + AmazonSQS sqs = AmazonSQSClientBuilder.standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .withRegion(Regions.US_EAST_1) + .build(); + + // Create a standard queue + + CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue"); + String standardQueueUrl = sqs.createQueue(createStandardQueueRequest) + .getQueueUrl(); + + System.out.println(standardQueueUrl); + + // Create a fifo queue + + Map queueAttributes = new HashMap(); + queueAttributes.put("FifoQueue", "true"); + queueAttributes.put("ContentBasedDeduplication", "true"); + + CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes); + String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest) + .getQueueUrl(); + + System.out.println(fifoQueueUrl); + + // Set up a dead letter queue + + String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue") + .getQueueUrl(); + + GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn")); + + String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes() + .get("QueueArn"); + + SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl) + .addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}"); + + sqs.setQueueAttributes(queueAttributesRequest); + + // Send a message to a standard queue + + Map messageAttributes = new HashMap<>(); + + messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute") + .withDataType("String")); + + SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl) + .withMessageBody("A simple message.") + .withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues + .withMessageAttributes(messageAttributes); + + sqs.sendMessage(sendMessageStandardQueue); + + // Send a message to a fifo queue + + SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl) + .withMessageBody("FIFO Queue") + .withMessageGroupId("baeldung-group-1") + .withMessageAttributes(messageAttributes); + + sqs.sendMessage(sendMessageFifoQueue); + + // Send multiple messages + + List messageEntries = new ArrayList<>(); + messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1") + .withMessageBody("batch-1") + .withMessageGroupId("baeldung-group-1")); + messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2") + .withMessageBody("batch-2") + .withMessageGroupId("baeldung-group-1")); + + SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries); + sqs.sendMessageBatch(sendMessageBatchRequest); + + // Read a message from a queue + + ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling; + .withMaxNumberOfMessages(1); // Max is 10 + + List sqsMessages = sqs.receiveMessage(receiveMessageRequest) + .getMessages(); + + sqsMessages.get(0) + .getAttributes(); + sqsMessages.get(0) + .getBody(); + + // Delete a message from a queue + + sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl) + .withReceiptHandle(sqsMessages.get(0) + .getReceiptHandle())); + + // Monitoring + GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All"); + GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest); + System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes() + .get("ApproximateNumberOfMessages"))); + System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes() + .get("ApproximateNumberOfMessagesNotVisible"))); + + } + +} diff --git a/cdi/pom.xml b/cdi/pom.xml index da0672afde..e96c3fc44e 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -44,41 +44,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - + 4.3.4.RELEASE 1.8.9 diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 924773cd02..cd71a9c123 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -236,41 +236,6 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/core-java-9/README.md b/core-java-9/README.md index 152b9f8841..d0758d585b 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -22,3 +22,4 @@ - [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles) - [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client) - [Method Handles in Java](http://www.baeldung.com/java-method-handles) +- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml index bf858047e9..11a111a245 100644 --- a/core-java-concurrency/pom.xml +++ b/core-java-concurrency/pom.xml @@ -183,41 +183,6 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/core-java-io/README.md b/core-java-io/README.md index 52485acfd5..84720e7b77 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -22,4 +22,6 @@ - [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor) - [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) - [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) -- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress) \ No newline at end of file +- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress) +- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path) +- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) diff --git a/core-java/README.md b/core-java/README.md index b9d87be785..4eb98b1b33 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -151,4 +151,5 @@ - [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) - [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - +- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) +- [The "final" Keyword in Java](http://www.baeldung.com/java-final) diff --git a/core-java/pom.xml b/core-java/pom.xml index f7bf9ed12a..05275e149d 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -235,6 +235,11 @@ h2 1.4.197 + + javax.mail + mail + 1.5.0-b01 + diff --git a/core-java/src/main/java/com/baeldung/assertion/Assertion.java b/core-java/src/main/java/com/baeldung/assertion/Assertion.java new file mode 100644 index 0000000000..795728757c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/assertion/Assertion.java @@ -0,0 +1,26 @@ +package com.baeldung.assertion; + +/** + * Simple demonstration of using Java assert keyword. + */ +public class Assertion { + + public static void main(String[] args) { + Assertion assertion = new Assertion(); + assertion.setup(); + } + + public void setup() { + Object conn = getConnection(); + assert conn != null : "Connection is null"; + + // continue with other setup ... + } + + // Simulate failure to get a connection; using Object + // to avoid dependencies on JDBC or some other heavy + // 3rd party library + public Object getConnection() { + return null; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DclSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DclSingleton.java new file mode 100644 index 0000000000..e10f111a56 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DclSingleton.java @@ -0,0 +1,38 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Double-checked locking design pattern applied to a singleton. + * + * @author Donato Rimenti + * + */ +public class DclSingleton { + + /** + * Current instance of the singleton. + */ + private static volatile DclSingleton instance; + + /** + * Private constructor to avoid instantiation. + */ + private DclSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static DclSingleton getInstance() { + if (instance == null) { + synchronized (DclSingleton.class) { + if (instance == null) { + instance = new DclSingleton(); + } + } + } + return instance; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DraconianSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DraconianSingleton.java new file mode 100644 index 0000000000..1d01c49b13 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DraconianSingleton.java @@ -0,0 +1,34 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Draconian singleton. The method to get the instance is synchronized. + * + * @author Donato Rimenti + * + */ +public class DraconianSingleton { + + /** + * Current instance of the singleton. + */ + private static DraconianSingleton instance; + + /** + * Private constructor to avoid instantiation. + */ + private DraconianSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static synchronized DraconianSingleton getInstance() { + if (instance == null) { + instance = new DraconianSingleton(); + } + return instance; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EarlyInitSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EarlyInitSingleton.java new file mode 100644 index 0000000000..18c4b7cdce --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EarlyInitSingleton.java @@ -0,0 +1,31 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Singleton with early initialization. Inlines the singleton instance + * initialization. + * + * @author Donato Rimenti + * + */ +public class EarlyInitSingleton { + + /** + * Current instance of the singleton. + */ + private static final EarlyInitSingleton INSTANCE = new EarlyInitSingleton(); + + /** + * Private constructor to avoid instantiation. + */ + private EarlyInitSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static EarlyInitSingleton getInstance() { + return INSTANCE; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EnumSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EnumSingleton.java new file mode 100644 index 0000000000..b7ff7f50b1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EnumSingleton.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Enum singleton pattern. Uses an enum to hold a reference to the singleton + * instance. + * + * @author Donato Rimenti + * + */ +public enum EnumSingleton { + + /** + * Current instance of the singleton. + */ + INSTANCE; +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/InitOnDemandSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/InitOnDemandSingleton.java new file mode 100644 index 0000000000..d76bada786 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/InitOnDemandSingleton.java @@ -0,0 +1,41 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Initialization on demand singleton pattern. Uses a nested static class to + * hold a reference to the singleton instance. + * + * @author Donato Rimenti + * + */ +public class InitOnDemandSingleton { + + /** + * Holder for a singleton instance. + * + * @author Donato Rimenti + * + */ + private static class InstanceHolder { + + /** + * Current instance of the singleton. + */ + private static final InitOnDemandSingleton INSTANCE = new InitOnDemandSingleton(); + } + + /** + * Private constructor to avoid instantiation. + */ + private InitOnDemandSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static InitOnDemandSingleton getInstance() { + return InstanceHolder.INSTANCE; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/mail/EmailService.java b/core-java/src/main/java/com/baeldung/mail/EmailService.java new file mode 100644 index 0000000000..e775b9f708 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/mail/EmailService.java @@ -0,0 +1,80 @@ +package com.baeldung.mail; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Properties; +import javax.mail.*; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; + +public class EmailService { + + private String host = ""; + private int port = 0; + private String username = ""; + private String password = ""; + + + public EmailService(String host, int port, String username, String password) { + + this.host = host; + this.port = port; + this.username = username; + this.password = password; + + sendMail(); + } + + private void sendMail() { + + Properties prop = new Properties(); + prop.put("mail.smtp.auth", true); + prop.put("mail.smtp.starttls.enable", "true"); + prop.put("mail.smtp.host", host); + prop.put("mail.smtp.port", port); + prop.put("mail.smtp.ssl.trust", host); + + Session session = Session.getInstance(prop, new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + + try { + + Message message = new MimeMessage(session); + message.setFrom(new InternetAddress("from@gmail.com")); + message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com")); + message.setSubject("Mail Subject"); + + String msg = "This is my first email using JavaMailer"; + + MimeBodyPart mimeBodyPart = new MimeBodyPart(); + mimeBodyPart.setContent(msg, "text/html"); + + MimeBodyPart attachmentBodyPart = new MimeBodyPart(); + attachmentBodyPart.attachFile(new File("pom.xml")); + + Multipart multipart = new MimeMultipart(); + multipart.addBodyPart(mimeBodyPart); + multipart.addBodyPart(attachmentBodyPart); + + message.setContent(multipart); + + Transport.send(message); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String ... args) { + new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitamin.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitamin.java new file mode 100644 index 0000000000..709e74eac0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitamin.java @@ -0,0 +1,50 @@ +package com.baeldung.optionalparams; + +public class MultiVitamin { + + private String name; // required + private int vitaminA; // in mcg + private int vitaminC; // in mg + private int calcium; // in mg + private int iron; // in mg + + public MultiVitamin(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public void setVitaminA(int vitaminA) { + this.vitaminA = vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public void setVitaminC(int vitaminC) { + this.vitaminC = vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public void setCalcium(int calcium) { + this.calcium = calcium; + } + + public int getIron() { + return iron; + } + + public void setIron(int iron) { + this.iron = iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminAllowingNulls.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminAllowingNulls.java new file mode 100644 index 0000000000..36d178783a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminAllowingNulls.java @@ -0,0 +1,38 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminAllowingNulls { + + private String name; // required + private Integer vitaminA; // in mcg + private Integer vitaminC; // in mg + private Integer calcium; // in mg + private Integer iron; // in mg + + public MultiVitaminAllowingNulls(String name, Integer vitaminA, Integer vitaminC, Integer calcium, Integer iron) { + this.name = name; + this.vitaminA = vitaminA; + this.vitaminC = vitaminC; + this.calcium = calcium; + this.iron = iron; + } + + public String getName() { + return name; + } + + public Integer getVitaminA() { + return vitaminA; + } + + public Integer getVitaminC() { + return vitaminC; + } + + public Integer getCalcium() { + return calcium; + } + + public Integer getIron() { + return iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminOverloading.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminOverloading.java new file mode 100644 index 0000000000..e1d3032fd3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminOverloading.java @@ -0,0 +1,56 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminOverloading { + + static final int DEFAULT_IRON_AMOUNT = 20; + + private final String name; // required + private final int vitaminA; // in mcg + private final int vitaminC; // in mg + private final int calcium; // in mg + private final int iron; // in mg + + public MultiVitaminOverloading(String name) { + this(name, 0); + } + + public MultiVitaminOverloading(String name, int vitaminA) { + this(name, vitaminA, 0); + } + + public MultiVitaminOverloading(String name, int vitaminA, int vitaminC) { + this(name, vitaminA, vitaminC, 0); + } + + public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium) { + this(name, vitaminA, vitaminC, calcium, DEFAULT_IRON_AMOUNT); + } + + public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium, int iron) { + this.name = name; + this.vitaminA = vitaminA; + this.vitaminC = vitaminC; + this.calcium = calcium; + this.iron = iron; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public int getIron() { + return iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminStaticFactoryMethods.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminStaticFactoryMethods.java new file mode 100644 index 0000000000..ca7ab0f6cf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminStaticFactoryMethods.java @@ -0,0 +1,52 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminStaticFactoryMethods { + + static final int IRON_AMT_DEF = 20; + static final int IRON_AMT_MEN = 30; + + static final int CALCIUM_AMT_DEF = 100; + static final int CALCIUM_AMT_WOMEN = 120; + + private final String name; // required + private final int vitaminA; // in mcg + private final int vitaminC; // in mg + private final int calcium; // in mg + private final int iron; // in mg + + public static MultiVitaminStaticFactoryMethods forMen(String name) { + return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_DEF, IRON_AMT_MEN); + } + + public static MultiVitaminStaticFactoryMethods forWomen(String name) { + return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_WOMEN, IRON_AMT_DEF); + } + + private MultiVitaminStaticFactoryMethods(String name, int vitaminA, int vitaminC, int calcium, int iron) { + this.name = name; + this.vitaminA = vitaminA; + this.vitaminC = vitaminC; + this.calcium = calcium; + this.iron = iron; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public int getIron() { + return iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminWithBuilder.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminWithBuilder.java new file mode 100644 index 0000000000..e1b2920e9a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminWithBuilder.java @@ -0,0 +1,77 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminWithBuilder { + + private final String name; // required + private final int vitaminA; // in mcg + private final int vitaminC; // in mg + private final int calcium; // in mg + private final int iron; // in mg + + private MultiVitaminWithBuilder(MultiVitaminBuilder builder) { + this.name = builder.name; + this.vitaminA = builder.vitaminA; + this.vitaminC = builder.vitaminC; + this.calcium = builder.calcium; + this.iron = builder.iron; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public int getIron() { + return iron; + } + + public static class MultiVitaminBuilder { + + private static final int ZERO = 0; + + private final String name; // required + private int vitaminA = ZERO; + private int vitaminC = ZERO; + private int calcium = ZERO; + private int iron = ZERO; + + public MultiVitaminBuilder(String name) { + this.name = name; + } + + public MultiVitaminBuilder withVitaminA(int vitaminA) { + this.vitaminA = vitaminA; + return this; + } + + public MultiVitaminBuilder withVitaminC(int vitaminC) { + this.vitaminC = vitaminC; + return this; + } + + public MultiVitaminBuilder withCalcium(int calcium) { + this.calcium = calcium; + return this; + } + + public MultiVitaminBuilder withIron(int iron) { + this.iron = iron; + return this; + } + + public MultiVitaminWithBuilder build() { + return new MultiVitaminWithBuilder(this); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java b/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java new file mode 100644 index 0000000000..0e1746fc38 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java @@ -0,0 +1,27 @@ +package com.baeldung.parameterpassing; + +public class NonPrimitives { + public static void main(String[] args) { + FooClass a = new FooClass(1); + FooClass b = new FooClass(1); + + System.out.printf("Before Modification: a = %d and b = %d ", a.num, b.num); + modify(a, b); + System.out.printf("\nAfter Modification: a = %d and b = %d ", a.num, b.num); + } + + public static void modify(FooClass a1, FooClass b1) { + a1.num++; + + b1 = new FooClass(1); + b1.num++; + } +} + +class FooClass { + public int num; + + public FooClass(int num) { + this.num = num; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java b/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java new file mode 100644 index 0000000000..f63229d7de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java @@ -0,0 +1,17 @@ +package com.baeldung.parameterpassing; + +public class Primitives { + public static void main(String[] args) { + int x = 1; + int y = 2; + + System.out.printf("Before Modification: x = %d and y = %d ", x, y); + modify(x, y); + System.out.printf("\nAfter Modification: x = %d and y = %d ", x, y); + } + + public static void modify(int x1, int y1) { + x1 = 5; + y1 = 10; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/designpatterns/singleton/synchronization/SingletonSynchronizationUnitTest.java b/core-java/src/test/java/com/baeldung/designpatterns/singleton/synchronization/SingletonSynchronizationUnitTest.java new file mode 100644 index 0000000000..2c1a3fe093 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/singleton/synchronization/SingletonSynchronizationUnitTest.java @@ -0,0 +1,119 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit tests for the singleton synchronization package with the same name. + * + * @author Donato Rimenti + * + */ +public class SingletonSynchronizationUnitTest { + + /** + * Size of the thread pools used. + */ + private static final int POOL_SIZE = 1_000; + + /** + * Number of tasks to submit. + */ + private static final int TASKS_TO_SUBMIT = 1_000_000; + + /** + * Tests the thread-safety of {@link DraconianSingleton}. + */ + @Test + public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(DraconianSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link DclSingleton}. + */ + @Test + public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(DclSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link EarlyInitSingleton}. + */ + @Test + public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link InitOnDemandSingleton}. + */ + @Test + public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(InitOnDemandSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link EnumSingleton}. + */ + @Test + public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(EnumSingleton.INSTANCE)); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java b/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java new file mode 100644 index 0000000000..e83ba7afc8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.java.clock; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.time.Clock; +import java.time.Duration; +import java.time.ZoneId; +import java.time.ZoneOffset; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ClockUnitTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClockUnitTest.class); + + @Test + public void givenClock_withSytemUTC_retrievesInstant() { + + Clock clockUTC = Clock.systemUTC(); + + assertEquals(clockUTC.getZone(), ZoneOffset.UTC); + assertEquals(clockUTC.instant().equals(null), false); + + LOGGER.debug("UTC instant :: " + clockUTC.instant()); + } + + @Test + public void givenClock_withSytem_retrievesInstant() { + + Clock clockSystem = Clock.system(ZoneId.of("Asia/Calcutta")); + + assertEquals(clockSystem.getZone(), ZoneId.of("Asia/Calcutta")); + assertEquals(clockSystem.instant().equals(null), false); + + LOGGER.debug("System zone :: " + clockSystem.getZone()); + } + + @Test + public void givenClock_withSytemDefaultZone_retrievesInstant() { + + Clock clockSystemDefault = Clock.systemDefaultZone(); + + assertEquals(clockSystemDefault.getZone().equals(null), false); + assertEquals(clockSystemDefault.instant().equals(null), false); + + LOGGER.debug("System Default instant :: " + clockSystemDefault.instant()); + } + + @Test + public void givenClock_withSytemUTC_retrievesTimeInMillis() { + + Clock clockMillis = Clock.systemDefaultZone(); + + assertEquals(clockMillis.instant().equals(null), false); + assertTrue(clockMillis.millis() > 0); + + LOGGER.debug("System Default millis :: " + clockMillis.millis()); + } + + @Test + public void givenClock_usingOffset_retrievesFutureDate() { + + Clock baseClock = Clock.systemDefaultZone(); + + // result clock will be later than baseClock + Clock futureClock = Clock.offset(baseClock, Duration.ofHours(72)); + + assertEquals(futureClock.instant().equals(null), false); + assertTrue(futureClock.millis() > baseClock.millis()); + + LOGGER.debug("Future Clock instant :: " + futureClock.instant()); + } + + @Test + public void givenClock_usingOffset_retrievesPastDate() { + Clock baseClock = Clock.systemDefaultZone(); + + // result clock will be later than baseClock + Clock pastClock = Clock.offset(baseClock, Duration.ofHours(-72)); + + assertEquals(pastClock.instant().equals(null), false); + assertTrue(pastClock.millis() < baseClock.millis()); + + LOGGER.debug("Past Clock instant :: " + pastClock.instant()); + } + + @Test + public void givenClock_usingTick_retrievesInstant() { + Clock clockDefaultZone = Clock.systemDefaultZone(); + Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(300)); + + assertEquals(clockDefaultZone.instant().equals(null), false); + assertEquals(clocktick.instant().equals(null), false); + assertTrue(clockDefaultZone.millis() > clocktick.millis()); + + LOGGER.debug("Clock Default Zone instant : " + clockDefaultZone.instant()); + LOGGER.debug("Clock tick instant: " + clocktick.instant()); + } + + @Test(expected=IllegalArgumentException.class) + public void givenClock_usingTickDurationNegative_throwsException() { + + Clock clockDefaultZone = Clock.systemDefaultZone(); + Clock.tick(clockDefaultZone, Duration.ofSeconds(-300)); + + } + + @Test + public void givenClock_usingTickSeconds_retrievesInstant() { + ZoneId zoneId = ZoneId.of("Asia/Calcutta"); + Clock tickSeconds = Clock.tickSeconds(zoneId); + + assertEquals(tickSeconds.instant().equals(null), false); + LOGGER.debug("Clock tick seconds instant :: " + tickSeconds.instant()); + + tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofSeconds(100)); + assertEquals(tickSeconds.instant().equals(null), false); + } + + @Test + public void givenClock_usingTickMinutes_retrievesInstant() { + + Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Calcutta")); + + assertEquals(tickMinutes.instant().equals(null), false); + LOGGER.debug("Clock tick seconds instant :: " + tickMinutes.instant()); + + tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofMinutes(5)); + assertEquals(tickMinutes.instant().equals(null), false); + } + + @Test + public void givenClock_usingWithZone_retrievesInstant() { + + ZoneId zoneSingapore = ZoneId.of("Asia/Singapore"); + Clock clockSingapore = Clock.system(zoneSingapore); + + assertEquals(clockSingapore.instant().equals(null), false); + LOGGER.debug("clockSingapore instant : " + clockSingapore.instant()); + + ZoneId zoneCalcutta = ZoneId.of("Asia/Calcutta"); + Clock clockCalcutta = clockSingapore.withZone(zoneCalcutta); + assertEquals(clockCalcutta.instant().equals(null), false); + LOGGER.debug("clockCalcutta instant : " + clockSingapore.instant()); + } + + @Test + public void givenClock_usingGetZone_retrievesZoneId() { + + Clock clockDefaultZone = Clock.systemDefaultZone(); + ZoneId zone = clockDefaultZone.getZone(); + + assertEquals(zone.getId().equals(null), false); + LOGGER.debug("Default zone instant : " + clockDefaultZone.instant()); + } +} diff --git a/core-java/src/test/java/com/baeldung/optionalparams/OptionalParamsUnitTest.java b/core-java/src/test/java/com/baeldung/optionalparams/OptionalParamsUnitTest.java new file mode 100644 index 0000000000..4f3c31822b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/optionalparams/OptionalParamsUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.optionalparams; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; + +import org.assertj.core.util.Arrays; +import org.junit.Test; + +public class OptionalParamsUnitTest { + + @Test + public void whenCreateMultiVitaminWithOverloading_thenOk() { + MultiVitaminOverloading multiVitamin = new MultiVitaminOverloading("Default Multivitamin"); + + assertThat(multiVitamin.getName()).isEqualTo("Default Multivitamin"); + assertThat(multiVitamin.getVitaminA()).isEqualTo(0); + assertThat(multiVitamin.getVitaminC()).isEqualTo(0); + assertThat(multiVitamin.getCalcium()).isEqualTo(0); + assertThat(multiVitamin.getIron()).isEqualTo(MultiVitaminOverloading.DEFAULT_IRON_AMOUNT); + } + + @Test + public void whenCreateMultiVitaminWithStaticFactoryMethods_thenOk() { + MultiVitaminStaticFactoryMethods mensMultiVitamin = MultiVitaminStaticFactoryMethods.forMen("Complete for Men"); + + assertThat(mensMultiVitamin.getName()).isEqualTo("Complete for Men"); + assertThat(mensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_DEF); + assertThat(mensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_MEN); + + MultiVitaminStaticFactoryMethods womensMultiVitamin = MultiVitaminStaticFactoryMethods.forWomen("Complete for Women"); + + assertThat(womensMultiVitamin.getName()).isEqualTo("Complete for Women"); + assertThat(womensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_WOMEN); + assertThat(womensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_DEF); + } + + @Test + public void whenCreateMultiVitaminWithBuilder_thenOk() { + MultiVitaminWithBuilder vitamin = new MultiVitaminWithBuilder.MultiVitaminBuilder("Maximum Strength") + .withCalcium(100) + .withIron(200) + .withVitaminA(50) + .withVitaminC(1000) + .build(); + + assertThat(vitamin.getName()).isEqualTo("Maximum Strength"); + assertThat(vitamin.getCalcium()).isEqualTo(100); + assertThat(vitamin.getIron()).isEqualTo(200); + assertThat(vitamin.getVitaminA()).isEqualTo(50); + assertThat(vitamin.getVitaminC()).isEqualTo(1000); + } + + @Test + public void whenCreateMutliVitaminWithAccessors_thenOk() { + MultiVitamin vitamin = new MultiVitamin("Generic"); + vitamin.setVitaminA(50); + vitamin.setVitaminC(1000); + vitamin.setCalcium(100); + vitamin.setIron(200); + + assertThat(vitamin.getName()).isEqualTo("Generic"); + assertThat(vitamin.getCalcium()).isEqualTo(100); + assertThat(vitamin.getIron()).isEqualTo(200); + assertThat(vitamin.getVitaminA()).isEqualTo(50); + assertThat(vitamin.getVitaminC()).isEqualTo(1000); + } + + @Test + public void whenCreateMultiVitaminWithNulls_thenOk() { + MultiVitamin vitamin = new MultiVitamin(null); + + assertThat(vitamin.getName()).isNull(); + } + + public void varArgsDemo() { + Object[] args = Arrays.array(Long.valueOf(1), Integer.valueOf(2), BigDecimal.valueOf(3)); + + processVarArgsWithCastingAntiPattern(args); + } + + private void processVarArgsWithCastingAntiPattern(Object... args) { + String message = "processing %s as %s"; + + // never do this sort of thing + for (Object arg : args) { + if (arg instanceof Long) { + System.out.println(String.format(message, arg, "Long")); + } else if (arg instanceof Integer) { + System.out.println(String.format(message, arg, "Integer")); + } else if (arg instanceof BigDecimal) { + System.out.println(String.format(message, arg, "BigDecimal")); + } + } + } +} diff --git a/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java b/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java new file mode 100644 index 0000000000..62f891d11b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.parameterpassing; + +import org.junit.Assert; +import org.junit.Test; + +public class NonPrimitivesUnitTest { + @Test + public void whenModifyingObjects_thenOriginalObjectChanged() { + Foo a = new Foo(1); + Foo b = new Foo(1); + + // Before Modification + Assert.assertEquals(a.num, 1); + Assert.assertEquals(b.num, 1); + + modify(a, b); + + // After Modification + Assert.assertEquals(a.num, 2); + Assert.assertEquals(b.num, 1); + } + + public static void modify(Foo a1, Foo b1) { + a1.num++; + + b1 = new Foo(1); + b1.num++; + } +} + +class Foo { + public int num; + + public Foo(int num) { + this.num = num; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java b/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java new file mode 100644 index 0000000000..496cd1d205 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.parameterpassing; + +import org.junit.Assert; +import org.junit.Test; + +public class PrimitivesUnitTest { + @Test + public void whenModifyingPrimitives_thenOriginalValuesNotModified() { + + int x = 1; + int y = 2; + + // Before Modification + Assert.assertEquals(x, 1); + Assert.assertEquals(y, 2); + + modify(x, y); + + // After Modification + Assert.assertEquals(x, 1); + Assert.assertEquals(y, 2); + } + + public static void modify(int x1, int y1) { + x1 = 5; + y1 = 10; + } +} diff --git a/core-kotlin/README.md b/core-kotlin/README.md index d6bd41a111..630d4c7436 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -24,3 +24,4 @@ - [Regular Expressions in Kotlin](http://www.baeldung.com/kotlin-regular-expressions) - [Objects in Kotlin](http://www.baeldung.com/kotlin-objects) - [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file) +- [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation) diff --git a/couchbase/README.md b/couchbase/README.md index f124a0192c..9b76609593 100644 --- a/couchbase/README.md +++ b/couchbase/README.md @@ -5,6 +5,7 @@ - [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring) - [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase) - [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view) +- [Querying Couchbase with N1QL](http://www.baeldung.com/n1ql-couchbase) ### Overview This Maven project contains the Java code for the Couchbase entities and Spring services diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 33eb7bb50a..c384347e91 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -139,33 +139,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - - - json - - - - - - - - 3.5 diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml index 8b6d3677c9..283b84c197 100644 --- a/ethereumj/pom.xml +++ b/ethereumj/pom.xml @@ -77,36 +77,6 @@ ethereumj - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - */EthControllerTestOne.java - - - - - - - - - - UTF-8 1.8 diff --git a/guava/README.md b/guava/README.md index 08814fd8b5..bb4e225649 100644 --- a/guava/README.md +++ b/guava/README.md @@ -32,3 +32,4 @@ - [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter) - [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) diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 19da678eb7..c201e87210 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -78,40 +78,4 @@ test - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index eb4c2ca2d3..a1bb74a3b5 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -994,32 +994,5 @@ - - integration - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntTest.java - - - - - - - - diff --git a/jjwt/pom.xml b/jjwt/pom.xml index cd2dd9f97e..7b90110b8f 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -45,39 +45,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index d19d03b3ff..2c9fb82126 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -72,7 +72,7 @@ org.apache.ignite - ignite-spring + ignite-spring-data ${ignite.version} @@ -192,7 +192,7 @@ 3.7.0 5.0 1.0.0 - 2.3.0 + 2.4.0 2.8.2 \ No newline at end of file diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/IgniteApp.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/IgniteApp.java new file mode 100644 index 0000000000..c181cdbb3c --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/IgniteApp.java @@ -0,0 +1,53 @@ +package com.baeldung.ignite.spring; + +import com.baeldung.ignite.spring.config.SpringDataConfig; +import com.baeldung.ignite.spring.dto.EmployeeDTO; +import com.baeldung.ignite.spring.repository.EmployeeRepository; +import org.apache.ignite.Ignite; +import org.apache.ignite.IgniteCache; +import org.apache.ignite.Ignition; +import org.apache.ignite.cache.query.QueryCursor; +import org.apache.ignite.cache.query.SqlFieldsQuery; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import java.util.List; + +/** + * Created by Gebruiker on 4/12/2018. + */ +public class IgniteApp { + + public static void main (String[] args) { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringDataConfig.class); + context.refresh(); + + EmployeeRepository repository = context.getBean(EmployeeRepository.class); + + EmployeeDTO employeeDTO = new EmployeeDTO(); + employeeDTO.setId(1); + employeeDTO.setName("John"); + employeeDTO.setEmployed(true); + + repository.save(employeeDTO.getId(), employeeDTO); + + EmployeeDTO employee = repository.getEmployeeDTOById(employeeDTO.getId()); + System.out.println(employee); + } + + private void getUsingTheCache(Integer employeeId) { + + Ignite ignite = Ignition.ignite(); + + IgniteCache cache = ignite.cache("baeldungCache"); + + EmployeeDTO employeeDTO = cache.get(employeeId); + + System.out.println(employeeDTO); + + SqlFieldsQuery sql = new SqlFieldsQuery( + "select * from EmployeeDTO where isEmployed = 'true'"); + + QueryCursor> cursor = cache.query(sql); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java new file mode 100644 index 0000000000..7627c91bc6 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.ignite.spring.config; + +import com.baeldung.ignite.spring.dto.EmployeeDTO; +import com.baeldung.ignite.spring.repository.EmployeeRepository; +import org.apache.ignite.Ignite; +import org.apache.ignite.Ignition; +import org.apache.ignite.configuration.CacheConfiguration; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.springdata.repository.config.EnableIgniteRepositories; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableIgniteRepositories(basePackageClasses = EmployeeRepository.class) +@ComponentScan(basePackages = "com.baeldung.ignite.spring.repository") +public class SpringDataConfig { + + @Bean + public Ignite igniteInstance() { + IgniteConfiguration config = new IgniteConfiguration(); + + CacheConfiguration cache = new CacheConfiguration("baeldungCache"); + + cache.setIndexedTypes(Integer.class, EmployeeDTO.class); + config.setCacheConfiguration(cache); + return Ignition.start(config); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/dto/EmployeeDTO.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/dto/EmployeeDTO.java new file mode 100644 index 0000000000..5dbf860fe7 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/dto/EmployeeDTO.java @@ -0,0 +1,48 @@ +package com.baeldung.ignite.spring.dto; + +import org.apache.ignite.cache.query.annotations.QuerySqlField; + +import java.io.Serializable; + +public class EmployeeDTO implements Serializable { + + @QuerySqlField(index = true) + private Integer id; + @QuerySqlField(index = true) + private String name; + @QuerySqlField(index = true) + private boolean isEmployed; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isEmployed() { + return isEmployed; + } + + public void setEmployed(boolean employed) { + isEmployed = employed; + } + + @Override + public String toString() { + return "EmployeeDTO{" + + "id=" + id + + ", name='" + name + '\'' + + ", isEmployed=" + isEmployed + + '}'; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/repository/EmployeeRepository.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/repository/EmployeeRepository.java new file mode 100644 index 0000000000..cdcd23a58a --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/repository/EmployeeRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.ignite.spring.repository; + +import com.baeldung.ignite.spring.dto.EmployeeDTO; +import org.apache.ignite.springdata.repository.IgniteRepository; +import org.apache.ignite.springdata.repository.config.RepositoryConfig; +import org.springframework.stereotype.Repository; + +@Repository +@RepositoryConfig(cacheName = "baeldungCache") +public interface EmployeeRepository extends IgniteRepository { + + EmployeeDTO getEmployeeDTOById(Integer id); +} diff --git a/libraries/README.md b/libraries/README.md index 7c06aa88ca..1bb3799075 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -59,12 +59,12 @@ - [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries) - [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) -- [Programatically Create, Configure, and Run a Tomcat Server] (http://www.baeldung.com/tomcat-programmatic-setup) +- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) - [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) - [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) -- [Introduction to Akka Actors in Java] (http://www.baeldung.com/akka-actors-java) +- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Asynchronous HTTP with async-http-client in Java](https://github.com/eugenp/tutorials/tree/master/libraries) - [Introduction to Smooks](http://www.baeldung.com/smooks) - [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) @@ -72,6 +72,8 @@ - [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) +- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) +- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 43c8239e96..c036c591ca 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -686,6 +686,12 @@ fugue 4.5.1 + + + org.jctools + jctools-core + ${jctools.version} + @@ -785,6 +791,52 @@ + + + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + @@ -856,6 +908,7 @@ 9.1.5.Final 4.1 1.4.9 + 2.1.2 1.10.L001 0.9.4.0006L diff --git a/libraries/src/main/java/com/baeldung/jctools/MpmcBenchmark.java b/libraries/src/main/java/com/baeldung/jctools/MpmcBenchmark.java new file mode 100644 index 0000000000..7b754bf709 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jctools/MpmcBenchmark.java @@ -0,0 +1,73 @@ +package com.baeldung.jctools; + +import org.jctools.queues.MpmcArrayQueue; +import org.jctools.queues.atomic.MpmcAtomicArrayQueue; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Control; + +import java.util.Queue; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SampleTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Fork(1) +@Warmup(iterations = 1) +@Measurement(iterations = 3) +@State(Scope.Group) +public class MpmcBenchmark { + + public static final String PARAM_UNSAFE = "MpmcArrayQueue"; + public static final String PARAM_AFU = "MpmcAtomicArrayQueue"; + public static final String PARAM_JDK = "ArrayBlockingQueue"; + + public static final int PRODUCER_THREADS_NUMBER = 32; + public static final int CONSUMER_THREADS_NUMBER = 32; + + public static final String GROUP_NAME = "MyGroup"; + + public static final int CAPACITY = 128; + + @Param({PARAM_UNSAFE, PARAM_AFU, PARAM_JDK}) + public volatile String implementation; + + public volatile Queue queue; + + @Setup(Level.Trial) + public void setUp() { + switch (implementation) { + case PARAM_UNSAFE: + queue = new MpmcArrayQueue<>(CAPACITY); + break; + case PARAM_AFU: + queue = new MpmcAtomicArrayQueue<>(CAPACITY); + break; + case PARAM_JDK: + queue = new ArrayBlockingQueue<>(CAPACITY); + break; + default: + throw new UnsupportedOperationException("Unsupported implementation " + implementation); + } + } + + + @Benchmark + @Group(GROUP_NAME) + @GroupThreads(PRODUCER_THREADS_NUMBER) + public void write(Control control) { + //noinspection StatementWithEmptyBody + while (!control.stopMeasurement && !queue.offer(1L)) { + // Is intentionally left blank + } + } + + @Benchmark + @Group(GROUP_NAME) + @GroupThreads(CONSUMER_THREADS_NUMBER) + public void read(Control control) { + //noinspection StatementWithEmptyBody + while (!control.stopMeasurement && queue.poll() == null) { + // Is intentionally left blank + } + } +} diff --git a/libraries/src/main/java/com/baeldung/jctools/README.md b/libraries/src/main/java/com/baeldung/jctools/README.md new file mode 100644 index 0000000000..3c1b3c1c1e --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jctools/README.md @@ -0,0 +1,7 @@ +## How to build and run the JMH benchmark + +Execute the following from the project's root: +```bash +mvn clean install +java -jar ./target/benchmarks.jar MpmcBenchmark -si true +``` \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java b/libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java new file mode 100644 index 0000000000..4a9d0fadb2 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.jctools; + +import org.jctools.queues.SpscArrayQueue; +import org.jctools.queues.SpscChunkedArrayQueue; +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.IntConsumer; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +public class JCToolsUnitTest { + + @Test + public void givenMultipleProducers_whenSpscQueueUsed_thenNoWarningOccurs() throws InterruptedException { + SpscArrayQueue queue = new SpscArrayQueue(2); + + Thread producer1 = new Thread(() -> { + queue.offer(1); + }); + producer1.start(); + producer1.join(); + + Thread producer2 = new Thread(() -> { + queue.offer(2); + }); + producer2.start(); + producer2.join(); + + Set fromQueue = new HashSet<>(); + Thread consumer = new Thread(() -> queue.drain(fromQueue::add)); + consumer.start(); + consumer.join(); + + assertThat(fromQueue).containsOnly(1, 2); + } + + @Test + public void whenQueueIsFull_thenNoMoreElementsCanBeAdded() throws InterruptedException { + SpscChunkedArrayQueue queue = new SpscChunkedArrayQueue<>(8, 16); + assertThat(queue.capacity()).isEqualTo(16); + + CountDownLatch startConsuming = new CountDownLatch(1); + CountDownLatch awakeProducer = new CountDownLatch(1); + AtomicReference error = new AtomicReference<>(); + Thread producer = new Thread(() -> { + IntStream.range(0, queue.capacity()).forEach(i -> { + assertThat(queue.offer(i)).isTrue(); + }); + assertThat(queue.offer(queue.capacity())).isFalse(); + startConsuming.countDown(); + try { + awakeProducer.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + assertThat(queue.offer(queue.capacity())).isTrue(); + }); + producer.setUncaughtExceptionHandler((t, e) -> { + error.set(e); + startConsuming.countDown(); + }); + producer.start(); + + startConsuming.await(); + + if (error.get() != null) { + fail("Producer's assertion failed", error.get()); + } + + Set fromQueue = new HashSet<>(); + queue.drain(fromQueue::add); + awakeProducer.countDown(); + producer.join(); + queue.drain(fromQueue::add); + + assertThat(fromQueue).containsAll(IntStream.range(0, 17).boxed().collect(Collectors.toSet())); + } +} diff --git a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java b/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java index ca723a7b7f..2818bb96a2 100644 --- a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java +++ b/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java @@ -52,16 +52,12 @@ public class EmbeddedChannelUnitTest { "/calculate?a=10&b=5"); wrongHttpRequest.headers().add("Operator", "Add"); - Throwable thrownException = catchThrowable(() -> { - // send invalid HTTP request to server and expect and error - channel.pipeline().fireChannelRead(wrongHttpRequest); - channel.checkException(); - Assertions.failBecauseExceptionWasNotThrown(UnsupportedOperationException.class); - }); - - assertThat(thrownException) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessage("HTTP method not supported"); + assertThatThrownBy(() -> { + // send invalid HTTP request to server and expect and error + channel.pipeline().fireChannelRead(wrongHttpRequest); + channel.checkException(); + }).isInstanceOf(UnsupportedOperationException.class) + .hasMessage("HTTP method not supported"); FullHttpResponse errorHttpResponse = channel.readOutbound(); String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset()); @@ -77,15 +73,11 @@ public class EmbeddedChannelUnitTest { "/calculate?a=10&b=5"); wrongHttpRequest.headers().add("Operator", "Invalid_operation"); - Throwable thrownException = catchThrowable(() -> { - // send invalid HTTP request to server and expect and error - channel.writeInbound(wrongHttpRequest); - Assertions.failBecauseExceptionWasNotThrown(IllegalArgumentException.class); - }); - - // the HttpMessageHandler does not handle the exception and throws it down the - // pipeline - assertThat(thrownException).isInstanceOf(IllegalArgumentException.class).hasMessage("Operation not defined"); + // the HttpMessageHandler does not handle the exception and throws it down the pipeline + assertThatThrownBy(() -> { + channel.writeInbound(wrongHttpRequest); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessage("Operation not defined"); // the outbound message is a HTTP response with the status code 500 FullHttpResponse errorHttpResponse = channel.readOutbound(); diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index ba67ccc2df..cacfa6ccfc 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -58,39 +58,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/maven/README.md b/maven/README.md new file mode 100644 index 0000000000..7c3779143a --- /dev/null +++ b/maven/README.md @@ -0,0 +1,9 @@ +### Relevant Articles + +- [Guide to the Core Maven Plugins](http://www.baeldung.com/core-maven-plugins) +- [Maven Resources Plugin](http://www.baeldung.com/maven-resources-plugin) +- [Maven Compiler Plugin](http://www.baeldung.com/maven-compiler-plugin) +- [Quick Guide to the Maven Surefire Plugin](http://www.baeldung.com/maven-surefire-plugin) +- [The Maven Failsafe Plugin](http://www.baeldung.com/maven-failsafe-plugin) +- [The Maven Verifier Plugin](http://www.baeldung.com/maven-verifier-plugin) +- [The Maven Clean Plugin](http://www.baeldung.com/maven-clean-plugin) diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml index 0e3936a73a..a7ae818960 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-5/pom.xml @@ -75,5 +75,45 @@ - + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + **/AutoconfigurationTest.java + **/*UnitTest.java + + + **/*IntegrationTest.java + */EthControllerTestOne.java + **/*IntTest.java + **/*EntryPointsTest.java + + + + + + + json + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 81e072c3a7..1937b1c5d8 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -43,41 +43,6 @@ java-cassandra - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - UTF-8 diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index 2b6f9651bc..1a0231f4a4 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -28,41 +28,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - Central diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 9784b2c5a8..b09e96262d 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -32,41 +32,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 1.8 1.8 diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index c2943875f1..0ae38a5323 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -163,40 +163,4 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 1358210a45..82fcc073cd 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -87,39 +87,4 @@ true - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml index bdd51e9659..7bd531638a 100644 --- a/persistence-modules/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -117,41 +117,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 1.8 1.8 diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index f1873a84d3..67ff243f73 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -98,41 +98,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 4.3.4.RELEASE diff --git a/pom.xml b/pom.xml index f0cb72e4d0..4183a3db49 100644 --- a/pom.xml +++ b/pom.xml @@ -482,4 +482,40 @@ + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleHandlerFilterFunction.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java similarity index 77% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleHandlerFilterFunction.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java index e55f5ce2fe..36b3c2ff6e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleHandlerFilterFunction.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.filter; +package com.baeldung.reactive.filters; import org.springframework.web.reactive.function.server.HandlerFilterFunction; import org.springframework.web.reactive.function.server.HandlerFunction; @@ -8,10 +8,10 @@ import reactor.core.publisher.Mono; import static org.springframework.http.HttpStatus.FORBIDDEN; -public class ExampleHandlerFilterFunction implements HandlerFilterFunction { +public class ExampleHandlerFilterFunction implements HandlerFilterFunction { @Override - public Mono filter(ServerRequest serverRequest, HandlerFunction handlerFunction) { + public Mono filter(ServerRequest serverRequest, HandlerFunction handlerFunction) { if (serverRequest.pathVariable("name").equalsIgnoreCase("test")) { return ServerResponse.status(FORBIDDEN).build(); } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleWebFilter.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java similarity index 93% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleWebFilter.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java index 99bc9f7fc3..8fe3550a7e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleWebFilter.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.filter; +package com.baeldung.reactive.filters; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/handler/PlayerHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java similarity index 77% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/handler/PlayerHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java index 51b4e166d1..20a08570ae 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/handler/PlayerHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.handler; +package com.baeldung.reactive.filters; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; @@ -8,9 +8,9 @@ import reactor.core.publisher.Mono; import static org.springframework.web.reactive.function.server.ServerResponse.ok; @Component -public class PlayerHandler { +class PlayerHandler { - public Mono getName(ServerRequest request) { + Mono getName(ServerRequest request) { Mono name = Mono.just(request.pathVariable("name")); return ok().body(name, String.class); } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/router/PlayerRouter.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java similarity index 74% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/router/PlayerRouter.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java index be721964ca..753991782c 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/router/PlayerRouter.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java @@ -1,7 +1,5 @@ -package com.baeldung.reactive.router; +package com.baeldung.reactive.filters; -import com.baeldung.reactive.filter.ExampleHandlerFilterFunction; -import com.baeldung.reactive.handler.PlayerHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.server.RouterFunction; @@ -17,6 +15,6 @@ public class PlayerRouter { public RouterFunction route(PlayerHandler playerHandler) { return RouterFunctions .route(GET("/players/{name}"), playerHandler::getName) - .filter(new ExampleHandlerFilterFunction()::filter); + .filter(new ExampleHandlerFilterFunction()); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/UserController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java similarity index 90% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/controller/UserController.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java index f51a674fe8..38c9210f88 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/UserController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.controller; +package com.baeldung.reactive.filters; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/handler/PlayerHandlerTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java similarity index 97% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/handler/PlayerHandlerTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java index de9b326874..8189802248 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/handler/PlayerHandlerTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.handler; +package com.baeldung.reactive.filters; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/controller/UserControllerTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java similarity index 96% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/controller/UserControllerTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java index 131a3d812b..d32a9d478f 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/controller/UserControllerTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.controller; +package com.baeldung.reactive.filters; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5/README.md b/spring-5/README.md index 566b905c74..d37927cfc7 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -12,7 +12,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) - [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/sring-5-enabledif) +- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/spring-5-enabledIf) - [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) - [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) - [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception) diff --git a/spring-akka/pom.xml b/spring-akka/pom.xml index 5efd111c35..551240ba73 100644 --- a/spring-akka/pom.xml +++ b/spring-akka/pom.xml @@ -51,41 +51,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 4.3.4.RELEASE 2.4.14 diff --git a/spring-all/pom.xml b/spring-all/pom.xml index b04ffae9c8..6c95817973 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -227,41 +227,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - org.baeldung.sample.App diff --git a/spring-bom/README.md b/spring-bom/README.md index 10e3502d11..d056216a2e 100644 --- a/spring-bom/README.md +++ b/spring-bom/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [Spring with Maven BOM] +- [Spring with Maven BOM](http://www.baeldung.com/spring-maven-bom) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 07466c76f2..00b6068bee 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -87,39 +87,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/AutoconfigurationTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - autoconfiguration diff --git a/spring-boot-gradle/README.md b/spring-boot-gradle/README.md new file mode 100644 index 0000000000..f96aa9ccf8 --- /dev/null +++ b/spring-boot-gradle/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 028fde5056..080c4d6353 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -1,4 +1,4 @@ -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: @@ -33,4 +33,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) +- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index f10fe5a909..936ea59fe7 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -200,39 +200,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/AutoconfigurationTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - autoconfiguration diff --git a/spring-boot/src/main/java/org/baeldung/model/User.java b/spring-boot/src/main/java/org/baeldung/model/User.java index 61936584c4..eb886338a0 100644 --- a/spring-boot/src/main/java/org/baeldung/model/User.java +++ b/spring-boot/src/main/java/org/baeldung/model/User.java @@ -15,6 +15,14 @@ public class User { private String name; private Integer status; + public User() { + } + + public User(String name, Integer status) { + this.name = name; + this.status = status; + } + public Integer getId() { return id; } diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index c9a06b5bab..a5cf6a0c24 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -1,10 +1,20 @@ package org.baeldung.repository; import org.baeldung.model.User; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; @@ -21,4 +31,54 @@ public interface UserRepository extends JpaRepository { @Async CompletableFuture findOneByStatus(Integer status); + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) + Collection findAllActiveUsersNative(); + + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + User findUserByStatusNative(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); + + @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); + + @Query("SELECT u FROM User u WHERE u.name like ?1%") + User findUserByNameLike(String name); + + @Query("SELECT u FROM User u WHERE u.name like :name%") + User findUserByNameLikeNamedParam(@Param("name") String name); + + @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + User findUserByNameLikeNative(String name); + + @Query(value = "SELECT u FROM User u") + List findAllUsers(Sort sort); + + @Query(value = "SELECT u FROM User u ORDER BY id") + Page findAllUsersWithPagination(Pageable pageable); + + @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + Page findAllUsersWithPaginationNative(Pageable pageable); + + @Modifying + @Query("update User u set u.status = :status where u.name = :name") + int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); + + @Modifying + @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNative(Integer status, String name); + } diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java index 2b61aa6252..f1e1ecce55 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -1,58 +1,65 @@ package org.baeldung.repository; -import org.baeldung.boot.Application; +import org.baeldung.boot.config.H2JpaConfig; import org.baeldung.model.User; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; +import org.springframework.data.mapping.PropertyReferenceException; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Created by adam. */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) +@SpringBootTest(classes = H2JpaConfig.class) public class UserRepositoryIntegrationTest { private final String USER_NAME_ADAM = "Adam"; + private final String USER_NAME_PETER = "Peter"; + private final Integer INACTIVE_STATUS = 0; private final Integer ACTIVE_STATUS = 1; - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; @Test - public void shouldReturnEmptyOptionalWhenSearchByNameInEmptyDB() { + public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() { Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - assertThat(foundUser.isPresent(), equalTo(false)); + assertThat(foundUser.isPresent()).isEqualTo(false); } @Test - public void shouldReturnOptionalWithPresentUserWhenExistsWithGivenName() { + public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() { User user = new User(); user.setName(USER_NAME_ADAM); userRepository.save(user); Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - assertThat(foundUser.isPresent(), equalTo(true)); - assertThat(foundUser.get().getName(), equalTo(USER_NAME_ADAM)); + assertThat(foundUser.isPresent()).isEqualTo(true); + assertThat(foundUser.get().getName()).isEqualTo(USER_NAME_ADAM); } @Test @Transactional - public void shouldReturnStreamOfUsersWithNameWhenExistWithSameGivenName() { + public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { User user1 = new User(); user1.setName(USER_NAME_ADAM); userRepository.save(user1); @@ -70,12 +77,12 @@ public class UserRepositoryIntegrationTest { userRepository.save(user4); try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count(), equalTo(3l)); + assertThat(foundUsersStream.count()).isEqualTo(3l); } } @Test - public void shouldReturnUserWithGivenStatusAsync() throws ExecutionException, InterruptedException { + public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { User user = new User(); user.setName(USER_NAME_ADAM); user.setStatus(ACTIVE_STATUS); @@ -83,8 +90,271 @@ public class UserRepositoryIntegrationTest { CompletableFuture userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); - assertThat(userByStatus.get().getName(), equalTo(USER_NAME_ADAM)); + assertThat(userByStatus.get().getName()).isEqualTo(USER_NAME_ADAM); + } + @Test + public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsers(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsersNative(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLike("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNative("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + + List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + assertThat(usersSortByName.get(0).getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test(expected = PropertyReferenceException.class) + public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + + userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + + userRepository.findAllUsers(new Sort("name")); + + List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + + Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); + + assertThat(usersPage.getContent().get(0).getName()).isEqualTo("SAMPLE1"); + } + + @Test + public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + + Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); + + assertThat(usersSortByNameLength.getContent().get(0).getName()).isEqualTo("SAMPLE1"); + } + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + + int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); } @After diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index c07380de56..128402926f 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -40,42 +40,5 @@ - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index 08d5e2b9be..4c9b50040e 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -40,40 +40,5 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 4d35e30be2..adf6b1e151 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -41,39 +41,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index 85baff12cd..aba98d05e4 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -60,42 +60,5 @@ - - - - integration - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + \ No newline at end of file diff --git a/spring-core/README.md b/spring-core/README.md index 0d984e87d4..b6804a4ce0 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -10,5 +10,6 @@ - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) - [Groovy Bean Definitions](http://www.baeldung.com/spring-groovy-beans) - [XML-Based Injection in Spring](http://www.baeldung.com/spring-xml-injection) -- [A Quick Guide to the Spring @Lazy Annotation] (http://www.baeldung.com/spring-lazy-annotation) +- [A Quick Guide to the Spring @Lazy Annotation](http://www.baeldung.com/spring-lazy-annotation) - [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton) +- [How to Inject a Property Value Into a Class Not Managed by Spring?](http://www.baeldung.com/inject-properties-value-non-spring-class) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index deffaf41db..ae1b93a403 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -90,42 +90,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + 1.10.19 1.4.4.RELEASE diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index df4723484d..f24d0318d3 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -66,39 +66,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-custom-aop/spring-custom-aop/pom.xml b/spring-custom-aop/spring-custom-aop/pom.xml index 95c1b7419f..b65e4c9f9b 100644 --- a/spring-custom-aop/spring-custom-aop/pom.xml +++ b/spring-custom-aop/spring-custom-aop/pom.xml @@ -138,43 +138,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - - + org.baeldung.boot.DemoApplication diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 7060ec5b36..9d772ee6ca 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -75,41 +75,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - UTF-8 diff --git a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java b/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java index b437dc4d7f..ee2c1f005a 100644 --- a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java +++ b/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java @@ -8,8 +8,6 @@ import java.util.Map; import javax.annotation.PostConstruct; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; -import javax.ejb.Lock; -import javax.ejb.LockType; import javax.ejb.Singleton; import javax.ejb.Startup; @@ -18,7 +16,7 @@ import javax.ejb.Startup; @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class CountryStateBeanManagedBean implements CountryState { - private volatile Map> countryStatesMap = new HashMap>(); + private final Map> countryStatesMap = new HashMap>(); @PostConstruct public synchronized void initialize() { diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index e3dd0d3f9a..a3cdfa172f 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -131,39 +131,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-jenkins-pipeline/pom.xml b/spring-jenkins-pipeline/pom.xml index 071f6e6e36..545d36e2b2 100644 --- a/spring-jenkins-pipeline/pom.xml +++ b/spring-jenkins-pipeline/pom.xml @@ -55,26 +55,6 @@ - - integration - - - - maven-surefire-plugin - - - **/*UnitTest.java - - - - **/*IntegrationTest.java - - - - - - - unit diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index 763465be8c..a3dad5802f 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -185,41 +185,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 3.8.6 1.4.193 diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 8c2949275c..8e8636edf7 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -30,41 +30,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 1.10.19 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 9b2981a747..9a4dc4870d 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -199,38 +199,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - live diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java new file mode 100644 index 0000000000..4a9f6a3431 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +@Configuration +public class CustomWebMvcConfigurationSupport extends WebMvcConfigurationSupport { + + @Bean + public RequestMappingHandlerMapping requestMappingHandlerMapping() { + RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping(); + handlerMapping.setUseSuffixPatternMatch(false); + return handlerMapping; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java new file mode 100644 index 0000000000..3867380665 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java @@ -0,0 +1,30 @@ +package com.baeldung.web.controller; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@RequestMapping("/site") +public class SiteController { + + @RequestMapping(value = "/{firstValue}/{secondValue}", method = RequestMethod.GET) + public String requestWithError(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } + + @RequestMapping(value = "/{firstValue}/{secondValue:.+}", method = RequestMethod.GET) + public String requestWithRegex(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } + + @RequestMapping(value = "/{firstValue}/{secondValue}/", method = RequestMethod.GET) + public String requestWithSlash(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } +} diff --git a/spring-mvc-kotlin/README.md b/spring-mvc-kotlin/README.md index b7cbcb1a7a..4e92117c52 100644 --- a/spring-mvc-kotlin/README.md +++ b/spring-mvc-kotlin/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Spring MVC Setup with Kotlin](http://www.baeldung.com/spring-mvc-kotlin) - [Working with Kotlin and JPA](https://github.com/eugenp/tutorials/tree/master/spring-mvc-kotlin) +- [Kotlin-allopen and Spring](http://www.baeldung.com/kotlin-allopen-spring) diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 7c517e2006..38edbe0aae 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -127,40 +127,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 1771c3e1f2..6f999f795d 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -51,41 +51,5 @@ - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 255aa840e7..34babbcf2c 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -72,43 +72,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*UnitTest.java - - - - - - - json - - - - - - - - + 19.0 3.5 diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index 3bd7ec07f6..02cab262d1 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -270,39 +270,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - live diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index b329bec07e..1ef3f924ad 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -289,39 +289,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - live diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index ebf174fb50..9a2169d46d 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -241,37 +241,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*IntegrationTest.java - **/*UnitTest.java - - - - - - - - - - live diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index b717a1366d..c3af96ebfc 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -169,39 +169,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - live diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index e46629f44d..1f680a8b89 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -37,39 +37,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index 50e2abfbfc..19bfad89b1 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -95,41 +95,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 3.3.2 diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml index 4262482617..9bf1478f58 100644 --- a/spring-spel/pom.xml +++ b/spring-spel/pom.xml @@ -30,39 +30,4 @@ test - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - \ No newline at end of file diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 2c37e73ada..9210186a98 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -10,6 +10,8 @@ - [Spring MVC + Thymeleaf 3.0: New Features](http://www.baeldung.com/spring-thymeleaf-3) - [How to Work with Dates in Thymeleaef](http://www.baeldung.com/dates-in-thymeleaf) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) +- [Working with Booleans in Thymeleaf](http://www.baeldung.com/working-with-booleans-in-thymeleaf) +- [Working with Fragments in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-fragments) ### Build the Project @@ -22,11 +24,12 @@ mvn cargo:run Access the pages using the URLs: -http://localhost:8082/spring-thymeleaf/ -http://localhost:8082/spring-thymeleaf/addStudent/ -http://localhost:8082/spring-thymeleaf/listStudents/ + - http://localhost:8082/spring-thymeleaf/ + - http://localhost:8082/spring-thymeleaf/addStudent/ + - http://localhost:8082/spring-thymeleaf/listStudents/ + - http://localhost:8082/spring-thymeleaf/booleans/ -The first URL is the home page of the application. The home page has links to the other two pages. +The first URL is the home page of the application. The home page has links to the second and third pages. ### Security The user/password required is: user1/user1Pass diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 5ce2a4b637..f6e7997da8 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -172,39 +172,4 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - \ No newline at end of file diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BooleanExpressionsController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BooleanExpressionsController.java new file mode 100644 index 0000000000..3a640e1499 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BooleanExpressionsController.java @@ -0,0 +1,45 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Controller to test boolean expressions + * + */ +@Controller +public class BooleanExpressionsController { + + @RequestMapping(value = "/booleans", method = RequestMethod.GET) + public String getDates(Model model) { + // "truthy" values + model.addAttribute("trueValue", true); + model.addAttribute("one", 1); + model.addAttribute("nonZeroCharacter", 'a'); + model.addAttribute("emptyString", ""); + model.addAttribute("foo", "foo"); + model.addAttribute("object", new Object()); + model.addAttribute("arrayOfZeros", new Integer[] { 0, 0 }); + model.addAttribute("arrayOfZeroAndOne", new Integer[] { 0, 1 }); + model.addAttribute("arrayOfOnes", new Integer[] { 1, 1 }); + + // "falsy" values + model.addAttribute("nullValue", null); + model.addAttribute("falseValue", false); + model.addAttribute("zero", 0); + model.addAttribute("zeroCharacter", '\0'); + model.addAttribute("falseString", "false"); + model.addAttribute("no", "no"); + model.addAttribute("off", "off"); + + model.addAttribute("isRaining", true); + model.addAttribute("isSunny", true); + model.addAttribute("isCold", false); + model.addAttribute("isWarm", true); + + return "booleans.html"; + } + +} diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/booleans.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/booleans.html new file mode 100644 index 0000000000..63d894421b --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/booleans.html @@ -0,0 +1,179 @@ + + + + +Expression utility objects + + + +

'Truthy' and 'falsy' expressions

+
    +
  • 'true' is evaluated to
  • +
  • '1' is evaluated to
  • +
  • non zero character is evaluated to
  • +
  • empty string is evaluated to
  • +
  • the string "foo" is evaluated to
  • +
  • an object is evaluated to
  • +
  • the array [0, 0] is evaluated to
  • +
  • the array [0, 1] is evaluated to
  • +
  • the array [1, 1] is evaluated to
  • + +
  • null value is evaluated to
  • +
  • 'false' is evaluated to
  • +
  • '0' is evaluated to
  • +
  • zero character is evaluated to
  • +
  • the string "false" is evaluated to
  • +
  • the string "no" is evaluated to
  • +
  • the string "off" is evaluated to
  • +
+ +

Using booleans as rendering conditions

+ + + + + + + + + + + + + + + + +
th:ifth:unless
truewill be renderedwon't be rendered
falsewon't be renderedwill be rendered
+ +

Boolean and conditional operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AB${A or B}${A} or ${B}${A and B}${A} and ${B}${!A}!${A}${not A}not ${A}
truetrue
truefalse
falsetrue
falsefalse
+ +
    +
  • the result of "true ? 'then'" is
  • +
  • the result of "false ? 'then'" is
  • +
  • the result of "true ? 'then' : 'else'" is
  • +
  • the result of "false ? 'then' : 'else'" is
  • +
  • the result of "'foo' ?: 'bar'" is
  • +
  • the result of "null ?: 'bar'" is
  • +
  • the result of "0 ?: 'bar'" is
  • +
  • the result of "1 ?: 'bar'" is
  • +
+ +
    +
  • The weather is bad
  • +
  • The weather is bad
  • +
  • The weather is good
  • +
  • The weather is good
  • +
  • It's warm
  • +
  • It's warm
  • +
  • It's warm
  • +
  • It's warm
  • +
  • It's
  • +
  • +
+ +

#bools utility object

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Array#bools.arrayIsTrue()#bools.arrayIsFalse()#bools.arrayAnd()#bools.arrayOr()
[0, 0]
[0, 1]
[1, 1]
+ + \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 72a4f0edac..67acd386f1 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -213,41 +213,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 4.2.0.RELEASE diff --git a/static-analysis/README.md b/static-analysis/README.md index 74cc64b90d..e4d4bc7bfc 100644 --- a/static-analysis/README.md +++ b/static-analysis/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Introduction to PMD](http://www.baeldung.com/pmd) +- [Java Static Analysis Tools in Eclipse and IntelliJ IDEA](http://www.baeldung.com/java-static-analysis-tools) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 85e628668a..0a9dccf666 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -11,4 +11,4 @@ - [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) - [JUnit Assert an Exception is Thrown](http://www.baeldung.com/junit-assert-exception) - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - +- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 2d119ae8af..62c338bcc9 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -15,41 +15,6 @@ ../../ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - UTF-8 diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 1006e9a373..b0d8c591fd 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -176,43 +176,6 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - - 2.8.5 1.8 diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index ea63ee0e58..b888cfa329 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -115,42 +115,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*UnitTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 2.8.5 diff --git a/vavr/README.md b/vavr/README.md index 373f897486..4bef25b625 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -1,8 +1,8 @@ ### Relevant Articles: -- [Introduction to Vavr](http://www.baeldung.com/javaslang) -- [Guide to Try in Vavr](http://www.baeldung.com/javaslang-try) -- [Guide to Pattern Matching in Vavr](http://www.baeldung.com/javaslang-pattern-matching) -- [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) +- [Introduction to Vavr](http://www.baeldung.com/vavr) +- [Guide to Try in Vavr](http://www.baeldung.com/vavr-try) +- [Guide to Pattern Matching in Vavr](http://www.baeldung.com/vavr-pattern-matching) +- [Property Testing Example With Vavr](http://www.baeldung.com/vavr-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) - [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) - [Introduction to Vavr’s Validation API](http://www.baeldung.com/vavr-validation-api)