diff --git a/.gitignore b/.gitignore index 90daf38dee..349efbcb67 100644 --- a/.gitignore +++ b/.gitignore @@ -84,4 +84,10 @@ software-security/sql-injection-samples/derby.log spring-soap/src/main/java/com/baeldung/springsoap/gen/ /report-*.json transaction.log -*-shell.log \ No newline at end of file +*-shell.log + +apache-cxf/cxf-aegis/baeldung.xml +apache-fop/src/test/resources/input.xml +apache-fop/src/test/resources/output_herold.pdf +apache-fop/src/test/resources/output_html2fo.pdf +apache-fop/src/test/resources/output_jtidy.pdf \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png index 7165a51782..12af62c131 100644 Binary files a/algorithms-miscellaneous-2/src/test/resources/graph.png and b/algorithms-miscellaneous-2/src/test/resources/graph.png differ diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index a1456c6b20..93426b3e0d 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -16,4 +16,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency) - [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search) - [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm) +- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) +- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search) - More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-4/README.md b/algorithms-miscellaneous-4/README.md index 6aad9a43e4..df2eafb733 100644 --- a/algorithms-miscellaneous-4/README.md +++ b/algorithms-miscellaneous-4/README.md @@ -1,7 +1,6 @@ ## Algorithms - Miscellaneous -This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and -[genetic algorithms](/../algorithms-genetic), have their own dedicated modules. +This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](https://github.com/eugenp/tutorials/blob/algorithms-sorting) and [genetic algorithms](https://github.com/eugenp/tutorials/blob/algorithms-genetic), have their own dedicated modules. ### Relevant articles: @@ -12,4 +11,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings) - [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters) - [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations) -- More articles: [[<-- prev]](/../algorithms-miscellaneous-3) [[next -->]](/../algorithms-miscellaneous-5) +- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5) diff --git a/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveInteger.java b/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveInteger.java new file mode 100644 index 0000000000..b08eea2a66 --- /dev/null +++ b/algorithms-miscellaneous-4/src/main/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveInteger.java @@ -0,0 +1,37 @@ +package com.baeldung.algorithms.smallestinteger; + +import java.util.Arrays; + +public class SmallestMissingPositiveInteger { + public static int searchInSortedArray(int[] input) { + for (int i = 0; i < input.length; i++) { + if (i != input[i]) { + return i; + } + } + + return input.length; + } + + public static int searchInUnsortedArraySortingFirst(int[] input) { + Arrays.sort(input); + return searchInSortedArray(input); + } + + public static int searchInUnsortedArrayBooleanArray(int[] input) { + boolean[] flags = new boolean[input.length]; + for (int number : input) { + if (number < flags.length) { + flags[number] = true; + } + } + + for (int i = 0; i < flags.length; i++) { + if (!flags[i]) { + return i; + } + } + + return flags.length; + } +} diff --git a/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveIntegerUnitTest.java b/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveIntegerUnitTest.java new file mode 100644 index 0000000000..8bb7151b41 --- /dev/null +++ b/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/smallestinteger/SmallestMissingPositiveIntegerUnitTest.java @@ -0,0 +1,88 @@ +package com.baeldung.algorithms.smallestinteger; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SmallestMissingPositiveIntegerUnitTest { + @Test + void givenArrayWithThreeMissing_whenSearchInSortedArray_thenThree() { + int[] input = new int[] {0, 1, 2, 4, 5}; + + int result = SmallestMissingPositiveInteger.searchInSortedArray(input); + + assertThat(result).isEqualTo(3); + } + + @Test + void givenArrayWithOneAndThreeMissing_whenSearchInSortedArray_thenOne() { + int[] input = new int[] {0, 2, 4, 5}; + + int result = SmallestMissingPositiveInteger.searchInSortedArray(input); + + assertThat(result).isEqualTo(1); + } + + @Test + void givenArrayWithoutMissingInteger_whenSearchInSortedArray_thenArrayLength() { + int[] input = new int[] {0, 1, 2, 3, 4, 5}; + + int result = SmallestMissingPositiveInteger.searchInSortedArray(input); + + assertThat(result).isEqualTo(input.length); + } + + @Test + void givenArrayWithThreeMissing_whenSearchInUnsortedArraySortingFirst_thenThree() { + int[] input = new int[] {1, 4, 0, 5, 2}; + + int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input); + + assertThat(result).isEqualTo(3); + } + + @Test + void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArraySortingFirst_thenOne() { + int[] input = new int[] {4, 2, 0, 5}; + + int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input); + + assertThat(result).isEqualTo(1); + } + + @Test + void givenArrayWithoutMissingInteger_whenSearchInUnsortedArraySortingFirst_thenArrayLength() { + int[] input = new int[] {4, 5, 1, 3, 0, 2}; + + int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input); + + assertThat(result).isEqualTo(input.length); + } + + @Test + void givenArrayWithThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenThree() { + int[] input = new int[] {1, 4, 0, 5, 2}; + + int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input); + + assertThat(result).isEqualTo(3); + } + + @Test + void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenOne() { + int[] input = new int[] {4, 2, 0, 5}; + + int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input); + + assertThat(result).isEqualTo(1); + } + + @Test + void givenArrayWithoutMissingInteger_whenSearchInUnsortedArrayBooleanArray_thenArrayLength() { + int[] input = new int[] {4, 5, 1, 3, 0, 2}; + + int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input); + + assertThat(result).isEqualTo(input.length); + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-5/README.md b/algorithms-miscellaneous-5/README.md index 7a8f2e0a36..598fbab8b5 100644 --- a/algorithms-miscellaneous-5/README.md +++ b/algorithms-miscellaneous-5/README.md @@ -8,4 +8,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings) - [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree) - [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers) +- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack) - More articles: [[<-- prev]](/../algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTree.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTree.java new file mode 100644 index 0000000000..84180473e2 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTree.java @@ -0,0 +1,33 @@ +package com.baeldung.algorithms.balancedbinarytree; + +public class BalancedBinaryTree { + + public static boolean isBalanced(Tree tree) { + return isBalancedRecursive(tree, -1).isBalanced; + } + + private static Result isBalancedRecursive(Tree tree, int depth) { + if (tree == null) { + return new Result(true, -1); + } + + Result leftSubtreeResult = isBalancedRecursive(tree.left(), depth + 1); + Result rightSubtreeResult = isBalancedRecursive(tree.right(), depth + 1); + + boolean isBalanced = Math.abs(leftSubtreeResult.height - rightSubtreeResult.height) <= 1; + boolean subtreesAreBalanced = leftSubtreeResult.isBalanced && rightSubtreeResult.isBalanced; + int height = Math.max(leftSubtreeResult.height, rightSubtreeResult.height) + 1; + + return new Result(isBalanced && subtreesAreBalanced, height); + } + + private static final class Result { + private final boolean isBalanced; + private final int height; + + private Result(boolean isBalanced, int height) { + this.isBalanced = isBalanced; + this.height = height; + } + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/Tree.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/Tree.java new file mode 100644 index 0000000000..8e091408c9 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/Tree.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.balancedbinarytree; + +public class Tree { + private final int value; + private final Tree left; + private final Tree right; + + public Tree(int value, Tree left, Tree right) { + this.value = value; + this.left = left; + this.right = right; + } + + public int value() { + return value; + } + + public Tree left() { + return left; + } + + public Tree right() { + return right; + } + + @Override + public String toString() { + return String.format("[%s, %s, %s]", + value, + left == null ? "null" : left.toString(), + right == null ? "null" : right.toString() + ); + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/binarygap/BinaryGap.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/binarygap/BinaryGap.java new file mode 100644 index 0000000000..e31e9870a0 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/binarygap/BinaryGap.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.binarygap; + +public class BinaryGap { + static int calculateBinaryGap(int n) { + return calculateBinaryGap(n >>> Integer.numberOfTrailingZeros(n), 0, 0); + } + + static int calculateBinaryGap(int n, int current, int maximum) { + if (n == 0) { + return maximum; + } else if ((n & 1) == 0) { + return calculateBinaryGap(n >>> 1, current + 1, maximum); + } else { + return calculateBinaryGap(n >>> 1, 0, Math.max(maximum, current)); + } + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java new file mode 100644 index 0000000000..25f313f991 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.balancedbinarytree; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider { + + @Test + public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() { + for (Tree tree : balancedTrees()) { + assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree)); + } + } + + @Test + public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() { + for (Tree tree : unbalancedTrees()) { + assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree)); + } + } + + private String toString(Tree tree) { + return tree != null ? tree.toString() : "null"; + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BinaryTreeDataProvider.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BinaryTreeDataProvider.java new file mode 100644 index 0000000000..3f4318afbc --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BinaryTreeDataProvider.java @@ -0,0 +1,69 @@ +package com.baeldung.algorithms.balancedbinarytree; + +import java.util.Arrays; +import java.util.Collection; + +class BinaryTreeDataProvider { + + static Collection balancedTrees() { + return Arrays.asList( + null, + leaf(1), + tree(1, leaf(2), leaf(3)), + tree( + 1, + leaf(2), + tree(3, leaf(4), null) + ), + tree( + 1, + tree( + 2, + tree(3, leaf(4), null), + leaf(5) + ), + tree( + 6, + leaf(7), + tree(8, null, leaf(9)) + ) + ) + ); + } + + static Collection unbalancedTrees() { + return Arrays.asList( + tree( + 1, + tree(2, leaf(3), null), + null + ), + tree( + 1, + tree( + 2, + tree(3, leaf(4), leaf(5)), + null + ), + tree(6, leaf(7), null) + ), + tree( + 1, + tree(2, leaf(3), null), + tree( + 4, + tree(5, leaf(6), leaf(7)), + null + ) + ) + ); + } + + private static Tree leaf(int value) { + return new Tree(value, null, null); + } + + private static Tree tree(int value, Tree left, Tree right) { + return new Tree(value, left, right); + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/binarygap/BinaryGapUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/binarygap/BinaryGapUnitTest.java new file mode 100644 index 0000000000..304d36e2bb --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/binarygap/BinaryGapUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.binarygap; + +import static com.baeldung.algorithms.binarygap.BinaryGap.calculateBinaryGap; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class BinaryGapUnitTest { + + @Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + + int result = calculateBinaryGap(63); + assertEquals(0, result); + } + + @Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + + int result = calculateBinaryGap(40); + assertEquals(1, result); + } + + @Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + + int result = calculateBinaryGap(9); + assertEquals(2, result); + } + + @Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + + int result = calculateBinaryGap(145); + assertEquals(3, result); + } + +} diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md index 3f27cfea49..15a5ec6e02 100644 --- a/algorithms-sorting/README.md +++ b/algorithms-sorting/README.md @@ -17,3 +17,4 @@ This module contains articles about sorting algorithms. - [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) - [Radix Sort in Java](https://www.baeldung.com/java-radix-sort) - [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort) diff --git a/apache-fop/src/test/resources/input.xml b/apache-fop/src/test/resources/input.xml deleted file mode 100644 index a8266f3f5c..0000000000 --- a/apache-fop/src/test/resources/input.xml +++ /dev/null @@ -1,1674 +0,0 @@ - -
- - Bootstrap a Web Application with Spring 4 - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. The Maven pom.xml - - - 3. The Java based Web Configuration - - - 4. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. The Maven pom.xml - - -     2.1. Justification of the cglib dependency - - -     2.2. The cglib dependency in Spring 3.2 and beyond - - - 3. The Java based web configuration - - -    3.1. The web.xml - - - 4. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - The tutorial illustrates how to Bootstrap a Web Application with Spring and also discusses how to make the jump from XML to Java without having to completely migrate the entire XML configuration. -
-
- <anchor xml:id="dbdoclet.2_The_Maven_pomxml"/><emphasis role="bold">2. The Maven pom.xml</emphasis> - <project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation=" - http://maven.apache.org/POM/4.0.0 - http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>org</groupId> - <artifactId>rest</artifactId> - <version>0.0.1-SNAPSHOT</version> - <packaging>war</packaging> - - <dependencies> - - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring-webmvc</artifactId> - <version>${spring.version}</version> - <exclusions> - <exclusion> - <artifactId>commons-logging</artifactId> - <groupId>commons-logging</groupId> - </exclusion> - </exclusions> - </dependency> - - </dependencies> - - <build> - <finalName>rest</finalName> - - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <version>3.1</version> - <configuration> - <source>1.6</source> - <target>1.6</target> - <encoding>UTF-8</encoding> - </configuration> - </plugin> - </plugins> - </build> - - <properties> - <spring.version>4.0.5.RELEASE</spring.version> - </properties> - -</project> -
- <emphasis role="bold">2.1. The cglib dependency before Spring 3.2</emphasis> - You may wonder why cglib is a dependency – it turns out there is a valid reason to include it – the entire configuration cannot function without it. If removed, Spring will throw: - Caused by: java.lang.IllegalStateException: CGLIB is required to process @Configuration classes. Either add CGLIB to the classpath or remove the following @Configuration bean definitions - The reason this happens is explained by the way Spring deals with @Configuration classes. These classes are effectively beans, and because of this they need to be aware of the Context, and respect scope and other bean semantics. This is achieved by dynamically creating a cglib proxy with this awareness for each @Configuration class, hence the cglib dependency. - Also, because of this, there are a few restrictions for Configuration annotated classes: - - - Configuration classes should not be final - - - They should have a constructor with no arguments - - -
-
- <emphasis role="bold">2.2. The cglib dependency in Spring 3.2 and beyond</emphasis> - Starting with Spring 3.2, it is no longer necessary to add cglib as an explicit dependency. This is because Spring is in now inlining cglib – which will ensure that all class based proxying functionality will work out of the box with Spring 3.2. - The new cglib code is placed under the Spring package: org.springframework.cglib (replacing the original net.sf.cglib). The reason for the package change is to avoid conflicts with any cglib versions already existing on the classpath. - Also, the new cglib 3.0 is now used, upgraded from the older 2.2 dependency (see this JIRA issue for more details). - Finally, now that Spring 4.0 is out in the wild, changes like this one (removing the cglib dependency) are to be expected with Java 8 just around the corner – you can watch this Spring Jira to keep track of the Spring support, and the Java 8 Resources page to keep tabs on the that. -
-
-
- <anchor xml:id="dbdoclet.3_The_Java_based_Web_Configuration"/><emphasis role="bold">3. The Java based Web Configuration</emphasis> - @Configuration -@ImportResource( { "classpath*:/rest_config.xml" } ) -@ComponentScan( basePackages = "org.rest" ) -@PropertySource({ "classpath:rest.properties", "classpath:web.properties" }) -public class AppConfig{ - - @Bean -   public static PropertySourcesPlaceholderConfigurer properties() { -   return new PropertySourcesPlaceholderConfigurer(); -   } -} - First, the @Configuration annotation – this is the main artifact used by the Java based Spring configuration; it is itself meta-annotated with @Component, which makes the annotated classes standard beans and as such, also candidates for component scanning. The main purpose of @Configuration classes is to be sources of bean definitions for the Spring IoC Container. For a more detailed description, see the official docs. - Then, @ImportResource is used to import the existing XML based Spring configuration. This may be configuration which is still being migrated from XML to Java, or simply legacy configuration that you wish to keep. Either way, importing it into the Container is essential for a successful migration, allowing small steps without to much risk. The equivalent XML annotation that is replaced is: - <import resource=”classpath*:/rest_config.xml” /> - Moving on to @ComponentScan – this configures the component scanning directive, effectively replacing the XML: - <context:component-scan base-package="org.rest" /> - As of Spring 3.1, the @Configuration are excluded from classpath scanning by default – see this JIRA issue. Before Spring 3.1 though, these classes should have been excluded explicitly: - excludeFilters = { @ComponentScan.Filter( Configuration.class ) } - The @Configuration classes should not be autodiscovered because they are already specified and used by the Container – allowing them to be rediscovered and introduced into the Spring context will result in the following error: - Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name ‘webConfig’ for bean class [org.rest.spring.AppConfig] conflicts with existing, non-compatible bean definition of same name and class [org.rest.spring.AppConfig] - And finally, using the @Bean annotation to configure the properties support – PropertySourcesPlaceholderConfigurer is initialized in a @Bean annotated method, indicating it will produce a Spring bean managed by the Container. This new configuration has replaced the following XML: - <context:property-placeholder -location="classpath:persistence.properties, classpath:web.properties" -ignore-unresolvable="true"/> - For a more in depth discussion on why it was necessary to manually register the PropertySourcesPlaceholderConfigurer bean, see the Properties with Spring Tutorial. -
- <emphasis role="bold">3.1. The web.xml</emphasis> - <?xml version="1.0" encoding="UTF-8"?> -<web-app xmlns=" - http://java.sun.com/xml/ns/javaee" -     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" -     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -    xsi:schemaLocation=" - http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" -    id="rest" version="3.0"> - - <context-param> - <param-name>contextClass</param-name> - <param-value> - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - </param-value> - </context-param> - <context-param> - <param-name>contextConfigLocation</param-name> - <param-value>org.rest.spring.root</param-value> - </context-param> - <listener> - <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> - </listener> - - <servlet> - <servlet-name>rest</servlet-name> - <servlet-class> - org.springframework.web.servlet.DispatcherServlet - </servlet-class> - <init-param> - <param-name>contextClass</param-name> - <param-value> - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - </param-value> - </init-param> - <init-param> - <param-name>contextConfigLocation</param-name> - <param-value>org.rest.spring.rest</param-value> - </init-param> - <load-on-startup>1</load-on-startup> - </servlet> - <servlet-mapping> - <servlet-name>rest</servlet-name> - <url-pattern>/api/*</url-pattern> - </servlet-mapping> - - <welcome-file-list> - <welcome-file /> - </welcome-file-list> - -</web-app> - First, the root context is defined and configured to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext. The newer AnnotationConfigWebApplicationContext accepts @Configuration annotated classes as input for the Container configuration and is needed in order to set up the Java based context. Unlike XmlWebApplicationContext, it assumes no default configuration class locations, so the “contextConfigLocation”init-param for the Servlet must be set. This will point to the java package where the @Configuration classes are located; the fully qualified name(s) of the classes are also supported. - Next, the DispatcherServlet is configured to use the same kind of context, with the only difference that it’s loading configuration classes out of a different package. - Other than this, the web.xml doesn’t really change from a XML to a Java based configuration. -
-
-
- <anchor xml:id="dbdoclet.4_Conclusion"/><emphasis role="bold">4. Conclusion</emphasis> - The presented approach allows for a smooth migration of the Spring configuration from XML to Java, mixing the old and the new. This is important for older projects, which may have a lot of XML based configuration that cannot be migrated all at once. - This way, in a migration, the XML beans can be ported in small increments. - In the next article on REST with Spring, I cover setting up MVC in the project, configuration of the HTTP status codes, payload marshalling and content negotiation. - The implementation of this Bootstrap a Spring Web App Tutorial can be downloaded as a working sample project. - This is an Eclipse based project, so it should be easy to import and run as it is. - -   - - - - - - - - - java, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
- -
- - Build a REST API with Spring 4 and Java Config - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. Understanding REST in Spring - - - 3. The Java configuration - - - 4. Testing the Spring context - - - 5. The Controller - - - 6. Mapping the HTTP response codes - - - 7. Additional Maven dependencies - - - 8. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - -   - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. Understanding REST in Spring - - - 3. The Java configuration - - - 4. Testing the Spring context - - - 5. The Controller - - - 6. Mapping the HTTP response codes - - -     6.1. Unmapped requests - - -     6.2. Valid, mapped requests - - -     6.3. Client error - - -     6.4. Using @ExceptionHandler - - - 7. Additional Maven dependencies - - - 8. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This article shows how to set up REST in Spring – the Controller and HTTP response codes, configuration of payload marshalling and content negotiation. -
-
- <anchor xml:id="dbdoclet.2_Understanding_REST_in_Spring"/><emphasis role="bold">2. Understanding REST in Spring</emphasis> - The Spring framework supports 2 ways of creating RESTful services: - - - using MVC with ModelAndView - - - using HTTP message converters - - - The ModelAndView approach is older and much better documented, but also more verbose and configuration heavy. It tries to shoehorn the REST paradigm into the old model, which is not without problems. The Spring team understood this and provided first-class REST support starting with Spring 3.0. - The new approach, based on HttpMessageConverterand annotations, is much more lightweight and easy to implement. Configuration is minimal and it provides sensible defaults for what you would expect from a RESTful service. It is however newer and a a bit on the light side concerning documentation; what’s , the reference doesn’t go out of it’s way to make the distinction and the tradeoffs between the two approaches as clear as they should be. Nevertheless, this is the way RESTful services should be build after Spring 3.0. -
-
- <anchor xml:id="dbdoclet.3_The_Java_configuration"/><emphasis role="bold">3. The Java configuration</emphasis> - - @Configuration -@EnableWebMvc -public class WebConfig{ - // -} - The new @EnableWebMvc annotation does a number of useful things – specifically, in the case of REST, it detect the existence of Jackson and JAXB 2 on the classpath and automatically creates and registers default JSON and XML converters. The functionality of the annotation is equivalent to the XML version: - <mvc:annotation-driven /> - This is a shortcut, and though it may be useful in many situations, it’s not perfect. When more complex configuration is needed, remove the annotation and extend WebMvcConfigurationSupport directly. -
-
- <anchor xml:id="dbdoclet.4_Testing_the_Spring_context"/><emphasis role="bold">4. Testing the Spring context</emphasis> - Starting with Spring 3.1, we get first-class testing support for @Configuration classes: - @RunWith( SpringJUnit4ClassRunner.class ) -@ContextConfiguration( classes = { ApplicationConfig.class, PersistenceConfig.class }, - loader = AnnotationConfigContextLoader.class ) -public class SpringTest{ - - @Test - public void whenSpringContextIsInstantiated_thenNoExceptions(){ - // When - } -} - The Java configuration classes are simply specified with the @ContextConfiguration annotation and the new AnnotationConfigContextLoader loads the bean definitions from the @Configuration classes. - Notice that the WebConfig configuration class was not included in the test because it needs to run in a Servlet context, which is not provided. -
-
- <anchor xml:id="dbdoclet.5_The_Controller"/><emphasis role="bold">5. The Controller</emphasis> - The @Controller is the central artifact in the entire Web Tier of the RESTful API. For the purpose of this post, the controller is modeling a simple REST resource – Foo: - @Controller -@RequestMapping( value = "/foos" ) -class FooController{ - - @Autowired - IFooService service; - - @RequestMapping( method = RequestMethod.GET ) - @ResponseBody - public List< Foo > findAll(){ - return service.findAll(); - } - - @RequestMapping( value = "/{id}", method = RequestMethod.GET ) - @ResponseBody - public Foo findOne( @PathVariable( "id" ) Long id ){ - return RestPreconditions.checkFound( service.findOne( id ) ); - } - - @RequestMapping( method = RequestMethod.POST ) - @ResponseStatus( HttpStatus.CREATED ) - @ResponseBody - public Long create( @RequestBody Foo resource ){ - Preconditions.checkNotNull( resource ); - return service.create( resource ); - } - - @RequestMapping( value = "/{id}", method = RequestMethod.PUT ) - @ResponseStatus( HttpStatus.OK ) - public void update( @PathVariable( "id" ) Long id, @RequestBody Foo resource ){ - Preconditions.checkNotNull( resource ); - RestPreconditions.checkNotNull( service.getById( resource.getId() ) ); - service.update( resource ); - } - - @RequestMapping( value = "/{id}", method = RequestMethod.DELETE ) - @ResponseStatus( HttpStatus.OK ) - public void delete( @PathVariable( "id" ) Long id ){ - service.deleteById( id ); - } - -} - You may have noticed I’m using a very simple, guava style RestPreconditions utility: - public class RestPreconditions { - public static <T> T checkFound(final T resource) { - if (resource == null) { - throw new MyResourceNotFoundException(); - } - return resource; - } -} - The Controller implementation is non-public – this is because it doesn’t need to be. Usually the controller is the last in the chain of dependencies – it receives HTTP requests from the Spring front controller (the DispathcerServlet) and simply delegate them forward to a service layer. If there is no use case where the controller has to be injected or manipulated through a direct reference, then I prefer not to declare it as public. - The request mappings are straightforward – as with any controller, the actual value of the mapping as well as the HTTP method are used to determine the target method for the request. @RequestBody will bind the parameters of the method to the body of the HTTP request, whereas @ResponseBody does the same for the response and return type. They also ensure that the resource will be marshalled and unmarshalled using the correct HTTP converter. Content negotiation will take place to choose which one of the active converters will be used, based mostly on the Accept header, although other HTTP headers may be used to determine the representation as well. -
-
- <anchor xml:id="dbdoclet.6_Mapping_the_HTTP_response_codes"/><emphasis role="bold">6. Mapping the HTTP response codes</emphasis> - The status codes of the HTTP response are one of the most important parts of the REST service, and the subject can quickly become very complex. Getting these right can be what makes or breaks the service. -
- <emphasis role="bold">6.1. Unmapped requests</emphasis> - If Spring MVC receives a request which doesn’t have a mapping, it considers the request not to be allowed and returns a 405 METHOD NOT ALLOWED back to the client. It is also good practice to include the Allow HTTP header when returning a 405 to the client, in order to specify which operations are allowed. This is the standard behavior of Spring MVC and does not require any additional configuration. -
-
- <emphasis role="bold">6.2. Valid, mapped requests</emphasis> - For any request that does have a mapping, Spring MVC considers the request valid and responds with 200 OK if no other status code is specified otherwise. It is because of this that controller declares different @ResponseStatus for the create, update and delete actions but not for get, which should indeed return the default 200 OK. -
-
- <emphasis role="bold">6.3. Client error</emphasis> - In case of a client error, custom exceptions are defined and mapped to the appropriate error codes. Simply throwing these exceptions from any of the layers of the web tier will ensure Spring maps the corresponding status code on the HTTP response. - @ResponseStatus( value = HttpStatus.BAD_REQUEST ) -public class BadRequestException extends RuntimeException{ - // -} -@ResponseStatus( value = HttpStatus.NOT_FOUND ) -public class ResourceNotFoundException extends RuntimeException{ - // -} - These exceptions are part of the REST API and, as such, should only be used in the appropriate layers corresponding to REST; if for instance a DAO/DAL layer exist, it should not use the exceptions directly. Note also that these are not checked exceptions but runtime exceptions – in line with Spring practices and idioms. -
-
- <emphasis role="bold">6.4. Using @ExceptionHandler</emphasis> - Another option to map custom exceptions on specific status codes is to use the @ExceptionHandler annotation in the controller. The problem with that approach is that the annotation only applies to the controller in which it is defined, not to the entire Spring Container, which means that it needs to be declared in each controller individually. This quickly becomes cumbersome, especially in more complex applications which many controllers. There are a few JIRA issues opened with Spring at this time to handle this and other related limitations: SPR-8124, SPR-7278, SPR-8406. -
-
-
- <anchor xml:id="dbdoclet.7_Additional_Maven_dependencies"/><emphasis role="bold">7. Additional Maven dependencies</emphasis><emphasis role="bold"></emphasis> - In addition to the spring-webmvc dependency required for the standard web application, we’ll need to set up content marshalling and unmarshalling for the REST API: - <dependencies> - <dependency> -   <groupId>com.fasterxml.jackson.core</groupId> -    <artifactId>jackson-databind</artifactId> -   <version>${jackson.version}</version> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - <version>${jaxb-api.version}</version> - <scope>runtime</scope> - </dependency> -</dependencies> - -<properties> - <jackson.version>2.4.0</jackson.version> - <jaxb-api.version>2.2.11</jaxb-api.version> -</properties> - These are the libraries used to convert the representation of the REST resource to either JSON or XML. -
-
- <anchor xml:id="dbdoclet.8_Conclusion"/><emphasis role="bold">8. Conclusion</emphasis> - This tutorial illustrated how to implement and configure a REST Service using Spring 4 and Java based configuration, discussing HTTP response codes, basic Content Negotiation and marshaling. - In the next articles of the series I will focus on Discoverability of the API, advanced content negotiation and working with additional representations of a Resource. - The implementation of this Spring REST API Tutorial can be downloaded as a working sample project. - This is an Eclipse based project, so it should be easy to import and run as it is. - - - - - - - - - - java, REST, Spring, testing - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - - - -
-
-
- -
- - Spring Security for a REST API - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. Spring Security in the web.xml - - - 3. The Security Configuration - - - 4. Maven and other trouble - - - 5. Conclusion - - - - - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. Introducing Spring Security in the web.xml - - - 3. The Security Configuration - - -     3.1. The basics - - -     3.2. The Entry Point - - -     3.3. The Login - - -     3.4. Authentication should return 200 instead of 301 - - -     3.5. Failed Authentication should return 401 instead of 302 - - -     3.6. The Authentication Manager and Provider - - -     3.7. Finally – Authentication against the running REST Service - - - 4. Maven and other trouble - - - 5. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This tutorial shows how to Secure a REST Service using Spring and Spring Security 3.1 with Java based configuration. The article will focus on how to set up the Security Configuration specifically for the REST API using a Login and Cookie approach. -
-
- <anchor xml:id="dbdoclet.2_Spring_Security_in_the_webxml"/><emphasis role="bold">2. Spring Security in the web.xml</emphasis> - The architecture of Spring Security is based entirely on Servlet Filters and, as such, comes before Spring MVC in regards to the processing of HTTP requests. Keeping this in mind, to begin with, a filter needs to be declared in the web.xml of the application: - <filter> - <filter-name>springSecurityFilterChain</filter-name> - <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> -</filter> -<filter-mapping> - <filter-name>springSecurityFilterChain</filter-name> - <url-pattern>/*</url-pattern> -</filter-mapping> - The filter must necessarily be named ‘springSecurityFilterChain’  to match the default bean created by Spring Security in the container. - Note that the defined filter is not the actual class implementing the security logic but a DelegatingFilterProxy with the purpose of delegating the Filter’s methods to an internal bean. This is done so that the target bean can still benefit from the Spring context lifecycle and flexibility. - The URL pattern used to configure the Filter is /* even though the entire web service is mapped to /api/* so that the security configuration has the option to secure other possible mappings as well, if required. -
-
- <anchor xml:id="dbdoclet.3_The_Security_Configuration"/><emphasis role="bold">3. The Security Configuration</emphasis> - <?xml version="1.0" encoding="UTF-8"?> -<beans:beans - xmlns="http://www.springframework.org/schema/security" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:beans="http://www.springframework.org/schema/beans" - xmlns:sec="http://www.springframework.org/schema/security" - xsi:schemaLocation=" - http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-3.2.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> - - <http entry-point-ref="restAuthenticationEntryPoint"> - <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN"/> - - <form-login - authentication-success-handler-ref="mySuccessHandler" - authentication-failure-handler-ref="myFailureHandler" - /> - - <logout /> - </http> - - <beans:bean id="mySuccessHandler" - class="org.rest.security.MySavedRequestAwareAuthenticationSuccessHandler"/> - <beans:bean id="myFailureHandler" - class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/> - - <authentication-manager alias="authenticationManager"> - <authentication-provider> - <user-service> - <user name="temporary" password="temporary" authorities="ROLE_ADMIN"/> - <user name="user" password="user" authorities="ROLE_USER"/> - </user-service> - </authentication-provider> - </authentication-manager> - -</beans:beans> - Most of the configuration is done using the security namespace – for this to be enabled, the schema locations must be defined and pointed to the correct 3.1 or 3.2 XSD versions. The namespace is designed so that it expresses the common uses of Spring Security while still providing hooks raw beans to accommodate more advanced scenarios. >> Signup for my upcoming Video Course on Building a REST API with Spring 4 -
- <emphasis role="bold">3.1. The <http> element</emphasis> - The <http> element is the main container element for HTTP security configuration. In the current implementation, it only secured a single mapping: /api/admin/**. Note that the mapping is relative to the root context of the web application, not to the rest Servlet; this is because the entire security configuration lives in the root Spring context and not in the child context of the Servlet. -
-
- <emphasis role="bold">3.2. The Entry Point</emphasis> - In a standard web application, the authentication process may be automatically triggered when the client tries to access a secured resource without being authenticated – this is usually done by redirecting to a login page so that the user can enter credentials. However, for a REST Web Service this behavior doesn’t make much sense – Authentication should only be done by a request to the correct URI and all other requests should simply fail with a 401 UNAUTHORIZED status code if the user is not authenticated. - Spring Security handles this automatic triggering of the authentication process with the concept of an Entry Point – this is a required part of the configuration, and can be injected via the entry-point-ref attribute of the <http> element. Keeping in mind that this functionality doesn’t make sense in the context of the REST Service, the new custom entry point is defined to simply return 401 whenever it is triggered: - @Component( "restAuthenticationEntryPoint" ) -public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{ - - @Override - public void commence( HttpServletRequest request, HttpServletResponse response, - AuthenticationException authException ) throws IOException{ - response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); - } -} - A quick sidenote here is that the 401 is sent without the WWW-Authenticate header, as required by the HTTP Spec – we can of course set the value manually if we need to. -
-
- <emphasis role="bold">3.3. The Login Form for REST</emphasis> - There are multiple ways to do Authentication for a REST API – one of the default Spring Security provides is Form Login – which uses an authentication processing filter – org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter. - The <form-login> element will create this filter and will also allow us to set our custom authentication success handler on it. This can also be done manually by using the <custom-filter> element to register a filter at the position FORM_LOGIN_FILTER – but the namespace support is flexible enough. - Note that for a standard web application, the auto-config attribute of the <http> element is shorthand syntax for some useful security configuration. While this may be appropriate for some very simple configurations, it doesn’t fit and should not be used for a REST API. -
-
- <emphasis role="bold">3.4. Authentication should return 200 instead of 301</emphasis> - By default, form login will answer a successful authentication request with a 301 MOVED PERMANENTLY status code; this makes sense in the context of an actual login form which needs to redirect after login. For a RESTful web service however, the desired response for a successful authentication should be 200 OK. - This is done by injecting a custom authentication success handler in the form login filter, to replace the default one. The new handler implements the exact same login as the default org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler with one notable difference – the redirect logic is removed: - public class MySavedRequestAwareAuthenticationSuccessHandler - extends SimpleUrlAuthenticationSuccessHandler { - - private RequestCache requestCache = new HttpSessionRequestCache(); - - @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, - Authentication authentication) throws ServletException, IOException { - SavedRequest savedRequest = requestCache.getRequest(request, response); - - if (savedRequest == null) { - clearAuthenticationAttributes(request); - return; - } - String targetUrlParam = getTargetUrlParameter(); - if (isAlwaysUseDefaultTargetUrl() || - (targetUrlParam != null && - StringUtils.hasText(request.getParameter(targetUrlParam)))) { - requestCache.removeRequest(request, response); - clearAuthenticationAttributes(request); - return; - } - - clearAuthenticationAttributes(request); - } - - public void setRequestCache(RequestCache requestCache) { - this.requestCache = requestCache; - } -} -
-
- <emphasis role="bold">3.5. Failed Authentication should return 401 instead of 302</emphasis> - Similarly – we configured the authentication failure handler – same way we did with the success handler. - Luckily – in this case, we don’t need to actually define a new class for this handler – the standard implementation – SimpleUrlAuthenticationFailureHandler – does just fine. - The only difference is that – now that we’re defining this explicitly in our XML config – it’s not going to get a default defaultFailureUrl from Spring – and so it won’t redirect. -
-
- <emphasis role="bold">3.6. The Authentication Manager and Provider</emphasis> - The authentication process uses an in-memory provider to perform authentication – this is meant to simplify the configuration as a production implementation of these artifacts is outside the scope of this post. -
-
- <emphasis role="bold">3.7 Finally – Authentication against the running REST Service</emphasis> - Now let’s see how we can authenticate against the REST API – the URL for login is /j_spring_security_check – and a simple curl command performing login would be: - curl -i -X POST -d j_username=user -d j_password=userPass -http://localhost:8080/spring-security-rest/j_spring_security_check - This request will return the Cookie which will then be used by any subsequent request against the REST Service. - We can use curl to authentication and store the cookie it receives in a file: - curl -i -X POST -d j_username=user -d j_password=userPass -c /opt/cookies.txt -http://localhost:8080/spring-security-rest/j_spring_security_check - Then we can use the cookie from the file to do further authenticated requests: - curl -i --header "Accept:application/json" -X GET -b /opt/cookies.txt -http://localhost:8080/spring-security-rest/api/foos - This authenticated request will correctly result in a 200 OK: - HTTP/1.1 200 OK -Server: Apache-Coyote/1.1 -Content-Type: application/json;charset=UTF-8 -Transfer-Encoding: chunked -Date: Wed, 24 Jul 2013 20:31:13 GMT - -[{"id":0,"name":"JbidXc"}] -
-
-
- <anchor xml:id="dbdoclet.4_Maven_and_other_trouble"/><emphasis role="bold">4. Maven and other trouble</emphasis> - The Spring core dependencies necessary for a web application and for the REST Service have been discussed in detail. For security, we’ll need to add: spring-security-web and spring-security-config – all of these have also been covered in the Maven for Spring Security tutorial. - It’s worth paying close attention to the way Maven will resolve the older Spring dependencies – the resolution strategy will start causing problems once the security artifacts are added to the pom. To address this problem, some of the core dependencies will need to be overridden in order to keep them at the right version. -
-
- <anchor xml:id="dbdoclet.5_Conclusion"/><emphasis role="bold">5. Conclusion</emphasis> - This post covered the basic security configuration and implementation for a RESTful Service using Spring Security 3.1, discussing the web.xml, the security configuration, the HTTP status codes for the authentication process and the Maven resolution of the security artifacts. - The implementation of this Spring Security REST Tutorial can be downloaded as a working sample project.This is an Eclipse based project, so it should be easy to import and run as it is. - - - - - - - - - - REST, security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - - - -
-
-
- -
- - Spring Security Basic Authentication - - - - - - Return to Content - - - - - - Contents - - - 1. Overview - - - 2. The Spring Security Configuration - - - 3. Consuming The Secured Application - - - 4. Further Configuration – The Entry Point - - - 5. The Maven Dependencies - - - 6. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This tutorial shows how to set up, configure and customize Basic Authentication with Spring. We’re going to built on top of the simple Spring MVC example, and secure the UI of the MVC application with the Basic Auth mechanism provided by Spring Security. -
- <anchor xml:id="dbdoclet.2_The_Spring_Security_Configuration"/><emphasis role="bold">2. The Spring Security Configuration</emphasis> - The Configuration for Spring Security is still XML: - <?xml version="1.0" encoding="UTF-8"?> -<beans:beans xmlns="http://www.springframework.org/schema/security" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:beans="http://www.springframework.org/schema/beans" - xsi:schemaLocation=" - http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-3.1.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> - - <http use-expressions="true"> - <intercept-url pattern="/**" access="isAuthenticated()" /> - - <http-basic /> - </http> - - <authentication-manager> - <authentication-provider> - <user-service> - <user name="user1" password="user1Pass" authorities="ROLE_USER" /> - </user-service> - </authentication-provider> - </authentication-manager> - -</beans:beans> - This is one of the last pieces of configuration in Spring that still need XML – Java Configuration for Spring Security is still a work in progress. - What is relevant here is the <http-basic> element inside the main <http> element of the configuration – this is enough to enable Basic Authentication for the entire application. The Authentication Manager is not the focus of this tutorial, so we are using an in memory manager with the user and password defined in plaintext. - The web.xml of the web application enabling Spring Security has already been discussed in the Spring Logout tutorial. -
-
- <anchor xml:id="dbdoclet.3_Consuming_The_Secured_Application"/><emphasis role="bold">3. Consuming The Secured Application</emphasis> - The curl command is our go to tool for consuming the secured application. - First, let’s try to request the /homepage.html without providing any security credentials: - curl -i http://localhost:8080/spring-security-mvc-basic-auth/homepage.html - We get back the expected 401 Unauthorized and the Authentication Challenge: - HTTP/1.1 401 Unauthorized -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly -WWW-Authenticate: Basic realm="Spring Security Application" -Content-Type: text/html;charset=utf-8 -Content-Length: 1061 -Date: Wed, 29 May 2013 15:14:08 GMT - The browser would interpret this challenge and prompt us for credentials with a simple dialog, but since we’re using curl, this isn’t the case. - Now, let’s request the same resource – the homepage – but provide the credentials to access it as well: - curl -i --user user1:user1Pass http://localhost:8080/spring-security-mvc-basic-auth/homepage.html - Now, the response from the server is 200 OK along with a Cookie: - HTTP/1.1 200 OK -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly -Content-Type: text/html;charset=ISO-8859-1 -Content-Language: en-US -Content-Length: 90 -Date: Wed, 29 May 2013 15:19:38 GMT - From the browser, the application can be consumed normally – the only difference is that a login page is no longer a hard requirement since all browsers support Basic Authentication and use a dialog to prompt the user for credentials. -
-
- <anchor xml:id="dbdoclet.4_Further_Configuration_8211_The_Entry_Point"/><emphasis role="bold">4. Further Configuration – </emphasis><emphasis role="bold">The Entry Point</emphasis> - By default, the BasicAuthenticationEntryPoint provisioned by Spring Security returns a full html page for a 401 Unauthorized response back to the client. This html representation of the error renders well in a browser, but it not well suited for other scenarios, such as a REST API where a json representation may be preferred. - The namespace is flexible enough for this new requirement as well – to address this – the entry point can be overridden: - <http-basic entry-point-ref="myBasicAuthenticationEntryPoint" /> - The new entry point is defined as a standard bean: - @Component -public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { - - @Override - public void commence - (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) - throws IOException, ServletException { - response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - PrintWriter writer = response.getWriter(); - writer.println("HTTP Status 401 - " + authEx.getMessage()); - } - - @Override - public void afterPropertiesSet() throws Exception { - setRealmName("Baeldung"); - super.afterPropertiesSet(); - } -} - By writing directly to the HTTP Response we now have full control over the format of the response body. -
-
- <anchor xml:id="dbdoclet.5_The_Maven_Dependencies"/><emphasis role="bold">5. The Maven Dependencies</emphasis> - The Maven dependencies for Spring Security have been discussed before in the Spring Security with Maven article – we will need both spring-security-web and spring-security-config available at runtime. -
-
- <anchor xml:id="dbdoclet.6_Conclusion"/><emphasis role="bold">6. Conclusion</emphasis> - In this example we secured an MVC application with Spring Security and Basic Authentication. We discussed the XML configuration and we consumed the application with simple curl commands. Finally took control of the exact error message format – moving from the standard HTML error page to a custom text or json format. - The implementation of this Spring tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is. When the project runs locally, the sample html can be accessed at: - http://localhost:8080/spring-security-mvc-basic-auth/homepage.html - - - - - - - - - - security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
- -
- - Spring Security Digest Authentication - - - - - - Return to Content - - - - - - Contents - - - 1. Overview - - - 2. The Security XML Configuration - - - 3. Consuming the Secured Application - - - 4. The Maven Dependencies - - - 5. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This tutorial shows how to set up, configure and customize Digest Authentication with Spring. Similar to the previous article covering Basic Authentication, we’re going to built on top of the Spring MVC tutorial, and secure the application with the Digest Auth mechanism provided by Spring Security. -
- <anchor xml:id="dbdoclet.2_The_Security_XML_Configuration"/><emphasis role="bold">2. The Security XML Configuration</emphasis> - First thing to understand about the configuration is that, while Spring Security does have full out of the box support for the Digest authentication mechanism, this support is not as well integrated into the namespace as Basic Authentication was. - In this case, we need to manually define the raw beans that are going to make up the security configuration – the DigestAuthenticationFilter and the DigestAuthenticationEntryPoint: - <?xml version="1.0" encoding="UTF-8"?> -<beans:beans xmlns="http://www.springframework.org/schema/security" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:beans="http://www.springframework.org/schema/beans" - xsi:schemaLocation=" - http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-3.1.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> - -    <beans:bean id="digestFilter" - class="org.springframework.security.web.authentication.www.DigestAuthenticationFilter"> -        <beans:property name="userDetailsService" ref="userService" /> -        <beans:property name="authenticationEntryPoint" ref="digestEntryPoint" /> -    </beans:bean> -    <beans:bean id="digestEntryPoint"  - class="org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint"> -        <beans:property name="realmName" value="Contacts Realm via Digest Authentication" /> -        <beans:property name="key" value="acegi" /> -    </beans:bean> - - <!-- the security namespace configuration --> - <http use-expressions="true" entry-point-ref="digestEntryPoint"> - <intercept-url pattern="/**" access="isAuthenticated()" /> - - <custom-filter ref="digestFilter" after="BASIC_AUTH_FILTER" /> - </http> - - <authentication-manager> - <authentication-provider> - <user-service id="userService"> - <user name="user1" password="user1Pass" authorities="ROLE_USER" /> - </user-service> - </authentication-provider> - </authentication-manager> - -</beans:beans> - Next, we need to integrate these beans into the overall security configuration – and in this case, the namespace is still flexible enough to allow us to do that. - The first part of this is pointing to the custom entry point bean, via the entry-point-ref attribute of the main <http> element. - The second part is adding the newly defined digest filter into the security filter chain. Since this filter is functionally equivalent to the BasicAuthenticationFilter, we are using the same relative position in the chain – this is specified by the BASIC_AUTH_FILTER alias in the overall Spring Security Standard Filters. - Finally, notice that the Digest Filter is configured to point to the user service bean – and here, the namespace is again very useful as it allows us to specify a bean name for the default user service created by the <user-service> element: - <user-service id="userService"> -
-
- <anchor xml:id="dbdoclet.3_Consuming_the_Secured_Application"/><emphasis role="bold">3. Consuming the Secured Application</emphasis> - We’re going to be using the curl command to consume the secured application and understand how a client can interact with it. - Let’s start by requesting the homepage – without providing security credentials in the request: - curl -i http://localhost/spring-security-mvc-digest-auth/homepage.html - As expected, we get back a response with a 401 Unauthorized status code: - HTTP/1.1 401 Unauthorized -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=CF0233C...; Path=/spring-security-mvc-digest-auth/; HttpOnly -WWW-Authenticate: Digest realm="Contacts Realm via Digest Authentication", qop="auth", - nonce="MTM3MzYzODE2NTg3OTo3MmYxN2JkOWYxZTc4MzdmMzBiN2Q0YmY0ZTU0N2RkZg==" -Content-Type: text/html;charset=utf-8 -Content-Length: 1061 -Date: Fri, 12 Jul 2013 14:04:25 GMT - If this request were sent by the browser, the authentication challenge would prompt the user for credentials using a simple user/password dialog. - Let’s now provide the correct credentials and send the request again: - curl -i --digest --user - user1:user1Pass http://localhost/spring-security-mvc-digest-auth/homepage.html - Notice that we are enabling Digest Authentication for the curl command via the –digest flag. - The first response from the server will be the same – the 401 Unauthorized – but the challenge will now be interpreted and acted upon by a second request – which will succeed with a 200 OK: - HTTP/1.1 401 Unauthorized -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=A961E0D...; Path=/spring-security-mvc-digest-auth/; HttpOnly -WWW-Authenticate: Digest realm="Contacts Realm via Digest Authentication", qop="auth", - nonce="MTM3MzYzODgyOTczMTo3YjM4OWQzMGU0YTgwZDg0YmYwZjRlZWJjMDQzZWZkOA==" -Content-Type: text/html;charset=utf-8 -Content-Length: 1061 -Date: Fri, 12 Jul 2013 14:15:29 GMT - -HTTP/1.1 200 OK -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=55F996B...; Path=/spring-security-mvc-digest-auth/; HttpOnly -Content-Type: text/html;charset=ISO-8859-1 -Content-Language: en-US -Content-Length: 90 -Date: Fri, 12 Jul 2013 14:15:29 GMT - -<html> -<head></head> - -<body> - <h1>This is the homepage</h1> -</body> -</html> - A final note on this interaction is that a client can preemptively send the correct Authorization header with the first request, and thus entirely avoid the server security challenge and the second request. -
-
- <anchor xml:id="dbdoclet.4_The_Maven_Dependencies"/><emphasis role="bold">4. The Maven Dependencies</emphasis> - The security dependencies are discussed in depth in the Spring Security Maven tutorial. In short, we will need to define spring-security-web and spring-security-config as dependencies in our pom.xml. -
-
- <anchor xml:id="dbdoclet.5_Conclusion"/><emphasis role="bold">5. Conclusion</emphasis> - In this tutorial we introduce security into a simple Spring MVC project by leveraging the Digest Authentication support in the framework. - The implementation of these examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is. - When the project runs locally, the homepage html can be accessed at (or, with minimal Tomcat configuration, on port 80): - http://localhost:8080/spring-security-mvc-digest-auth/homepage.html - Finally, there is no reason an application needs to choose between Basic and Digest authentication – both can be set up simultaneously on the same URI structure, in such a way that the client can pick between the two mechanisms when consuming the web application. - - - - - - - - - - security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
- -
- - Basic and Digest Authentication for a REST Service with Spring Security - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. Configuration of Basic Authentication - - - 3. Configuration of Digest Authentication - - - 4. Supporting both authentication protocols in the same RESTful service - - - 5. Testing both scenarios - - - 6. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. Configuration of Basic Authentication - - -     2.1. Satisfying the stateless constraint – getting rid of sessions - - - 3. Configuration of Digest Authentication - - - 4. Supporting both authentication protocols in the same RESTful service - - -     4.1. Anonymous request - - -     4.2. Request with authentication credentials - - - 5. Testing both scenarios - - - 6. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This article discusses how to set up both Basic and Digest Authentication on the same URI structure of a REST API. In a previous article, we discussed another method of securing the REST Service – form based authentication, so Basic and Digest authentication is the natural alternative, as well as the more RESTful one. -
-
- <anchor xml:id="dbdoclet.2_Configuration_of_Basic_Authentication"/><emphasis role="bold">2. Configuration of Basic Authentication</emphasis> - The main reason that form based authentication is not ideal for a RESTful Service is that Spring Security will make use of Sessions – this is of course state on the server, so the statelessness constraints in REST is practically ignored. - We’ll start by setting up Basic Authentication – first we remove the old custom entry point and filter from the main <http> security element: - <http create-session="stateless"> - <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN" /> - - <http-basic /> -</http> - Note how support for basic authentication has been added with a single configuration line – <http-basic /> – which handles the creation and wiring of both the BasicAuthenticationFilter and the BasicAuthenticationEntryPoint. -
- <emphasis role="bold">2.1. Satisfying the stateless constraint – getting rid of sessions</emphasis> - One of the main constraints of the RESTful architectural style is that the client-server communication is fully stateless, as the original dissertation reads: -
-     5.1.3 Stateless - We next add a constraint to the client-server interaction: communication must be stateless in nature, as in the client-stateless-server (CSS) style of Section 3.4.3 (Figure 5-3), such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. -
- The concept of Session on the server is one with a long history in Spring Security, and removing it entirely has been difficult until now, especially when configuration was done by using the namespace. However, Spring Security 3.1 augments the namespace configuration with a new stateless option for session creation, which effectively guarantees that no session will be created or used by Spring. What this new option does is completely removes all session related filters from the security filter chain, ensuring that authentication is performed for each request. -
-
-
- <anchor xml:id="dbdoclet.3_Configuration_of_Digest_Authentication"/><emphasis role="bold">3. Configuration of Digest Authentication</emphasis> - Starting with the previous configuration, the filter and entry point necessary to set up digest authentication will be defined as beans. Then, the digest entry point will override the one created by <http-basic> behind the scenes. Finally, the custom digest filter will be introduced in the security filter chain using the after semantics of the security namespace to position it directly after the basic authentication filter. - <http create-session="stateless" entry-point-ref="digestEntryPoint"> - <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN" /> - - <http-basic /> - <custom-filter ref="digestFilter" after="BASIC_AUTH_FILTER" /> -</http> - -<beans:bean id="digestFilter" class= - "org.springframework.security.web.authentication.www.DigestAuthenticationFilter"> - <beans:property name="userDetailsService" ref="userService" /> - <beans:property name="authenticationEntryPoint" ref="digestEntryPoint" /> -</beans:bean> - -<beans:bean id="digestEntryPoint" class= - "org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint"> - <beans:property name="realmName" value="Contacts Realm via Digest Authentication"/> - <beans:property name="key" value="acegi" /> -</beans:bean> - -<authentication-manager> - <authentication-provider> - <user-service id="userService"> - <user name="eparaschiv" password="eparaschiv" authorities="ROLE_ADMIN" /> - <user name="user" password="user" authorities="ROLE_USER" /> - </user-service> - </authentication-provider> -</authentication-manager> - Unfortunately there is no support in the security namespace to automatically configure the digest authentication the way basic authentication can be configured with <http-basic>. Because of that, the necessary beans had to be defined and wired manually into the security configuration. -
-
- <anchor xml:id="dbdoclet.4_Supporting_both_authentication_protocols_in_the_same_RESTful_service"/><emphasis role="bold">4. Supporting both authentication protocols in the same RESTful service</emphasis> - Basic or Digest authentication alone can be easily implemented in Spring Security 3.x; it is supporting both of them for the same RESTful web service, on the same URI mappings that introduces a new level of complexity into the configuration and testing of the service. -
- <emphasis role="bold">4.1. Anonymous request</emphasis> - With both basic and digest filters in the security chain, the way a anonymous request – a request containing no authentication credentials (Authorization HTTP header) – is processed by Spring Security is – the two authentication filters will find no credentials and will continue execution of the filter chain. Then, seeing how the request wasn’t authenticated, an AccessDeniedException is thrown and caught in the ExceptionTranslationFilter, which commences the digest entry point, prompting the client for credentials. - The responsibilities of both the basic and digest filters are very narrow – they will continue to execute the security filter chain if they are unable to identify the type of authentication credentials in the request. It is because of this that Spring Security can have the flexibility to be configured with support for multiple authentication protocols on the same URI. - When a request is made containing the correct authentication credentials – either basic or digest – that protocol will be rightly used. However, for an anonymous request, the client will get prompted only for digest authentication credentials. This is because the digest entry point is configured as the main and single entry point of the Spring Security chain; as such digest authentication can be considered the default. -
-
- <emphasis role="bold">4.2. Request with authentication credentials</emphasis> - A request with credentials for Basic authentication will be identified by the Authorization header starting with the prefix “Basic”. When processing such a request, the credentials will be decoded in the basic authentication filter and the request will be authorized. Similarly, a request with credentials for Digest authentication will use the prefix “Digest”  for it’s Authorization header. -
-
-
- <anchor xml:id="dbdoclet.5_Testing_both_scenarios"/><emphasis role="bold">5. Testing both scenarios</emphasis> - The tests will consume the REST service by creating a new resource after authenticating with either basic or digest: - @Test -public void givenAuthenticatedByBasicAuth_whenAResourceIsCreated_then201IsReceived(){ - // Given - // When - Response response = given() - .auth().preemptive().basic( ADMIN_USERNAME, ADMIN_PASSWORD ) - .contentType( HttpConstants.MIME_JSON ).body( new Foo( randomAlphabetic( 6 ) ) ) - .post( paths.getFooURL() ); - - // Then - assertThat( response.getStatusCode(), is( 201 ) ); -} -@Test -public void givenAuthenticatedByDigestAuth_whenAResourceIsCreated_then201IsReceived(){ - // Given - // When - Response response = given() - .auth().digest( ADMIN_USERNAME, ADMIN_PASSWORD ) - .contentType( HttpConstants.MIME_JSON ).body( new Foo( randomAlphabetic( 6 ) ) ) - .post( paths.getFooURL() ); - - // Then - assertThat( response.getStatusCode(), is( 201 ) ); -} - Note that the test using basic authentication adds credentials to the request preemptively, regardless if the server has challenged for authentication or not. This is to ensure that the server doesn’t need to challenge the client for credentials, because if it did, the challenge would be for Digest credentials, since that is the default. -
-
- <anchor xml:id="dbdoclet.6_Conclusion"/><emphasis role="bold">6. Conclusion</emphasis> - This article covered the configuration and implementation of both Basic and Digest authentication for a RESTful service, using mostly Spring Security 3.0 namespace support as well as some new features added by Spring Security 3.1. - For the full implementation, check out the github project. - - - - - - - - - - REST, security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
diff --git a/apache-fop/src/test/resources/output_herold.pdf b/apache-fop/src/test/resources/output_herold.pdf deleted file mode 100644 index 1d23de7b61..0000000000 Binary files a/apache-fop/src/test/resources/output_herold.pdf and /dev/null differ diff --git a/apache-fop/src/test/resources/output_html2fo.pdf b/apache-fop/src/test/resources/output_html2fo.pdf deleted file mode 100644 index 7c2b4a0c51..0000000000 Binary files a/apache-fop/src/test/resources/output_html2fo.pdf and /dev/null differ diff --git a/apache-fop/src/test/resources/output_jtidy.pdf b/apache-fop/src/test/resources/output_jtidy.pdf deleted file mode 100644 index 1d9456122c..0000000000 Binary files a/apache-fop/src/test/resources/output_jtidy.pdf and /dev/null differ diff --git a/code-generation/pom.xml b/code-generation/pom.xml index b52e558b53..91ce0a4639 100644 --- a/code-generation/pom.xml +++ b/code-generation/pom.xml @@ -12,10 +12,16 @@ + + com.google.auto.value + auto-value-annotations + ${auto-value.version} + com.google.auto.value auto-value ${auto-value.version} + provided com.google.auto.factory @@ -43,9 +49,9 @@ - 1.3 - 1.0-beta5 - 1.0-rc5 + 1.6.6 + 1.0-beta6 + 1.0-rc6 4.2.0 diff --git a/code-generation/src/main/java/com/baeldung/autovalue/Person.java b/code-generation/src/main/java/com/baeldung/autovalue/Person.java new file mode 100644 index 0000000000..a5fb684596 --- /dev/null +++ b/code-generation/src/main/java/com/baeldung/autovalue/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.autovalue; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.google.auto.value.AutoValue; + +@AutoValue +public abstract class Person { + + public abstract String name(); + + public abstract List favoriteMovies(); + + public static Builder builder() { + return new AutoValue_Person.Builder(); + } + + @AutoValue.Builder + public static abstract class Builder { + + public abstract Builder name(String value); + + public abstract Builder favoriteMovies(List value); + + abstract List favoriteMovies(); + + abstract Person autoBuild(); + + public Person build() { + List favoriteMovies = favoriteMovies(); + List copy = Collections.unmodifiableList(new ArrayList<>(favoriteMovies)); + favoriteMovies(copy); + return autoBuild(); + } + } +} diff --git a/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java b/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java new file mode 100644 index 0000000000..fce12edafe --- /dev/null +++ b/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.autovalue; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +/** + * Unit Test which verifies that the {@link Person} value object creates defensive copies of its favoriteMovies list. + */ +public class PersonUnitTest { + + @Test + public void givenNewPerson_whenModifyOriginalList_thenValueObjectIsNotAlsoModified() { + // GIVEN new Person + List originalFavoriteMoviesList = new ArrayList(); + originalFavoriteMoviesList.add("Training Day"); + originalFavoriteMoviesList.add("Fast and the Furious"); + Person person = Person.builder() + .name("Dan") + .favoriteMovies(originalFavoriteMoviesList) + .build(); + + // WHEN modify original list + originalFavoriteMoviesList.add("Friday"); + + // THEN Person remains unaffected + assertFalse(person.favoriteMovies() + .contains("Friday")); + assertEquals(2, person.favoriteMovies() + .size()); + } + +} diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index f1984f18f4..95a00a1f5b 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts - [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings) - [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming) - [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services) +- [Categories in Groovy](https://www.baeldung.com/groovy-categories) - [[<-- Prev]](/core-groovy) diff --git a/core-groovy-collections/README.md b/core-groovy-collections/README.md index 4afd214e7d..aae8be508e 100644 --- a/core-groovy-collections/README.md +++ b/core-groovy-collections/README.md @@ -5,4 +5,6 @@ This module contains articles about Groovy core collections ## Relevant articles: - [Maps in Groovy](https://www.baeldung.com/groovy-maps) - +- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements) +- [Lists in Groovy](https://www.baeldung.com/groovy-lists) +- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy similarity index 95% rename from core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy index 9617c099ce..82a2138be4 100644 --- a/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy @@ -1,11 +1,11 @@ -package com.baeldung.lists +package com.baeldung.find -import com.baeldung.Person +import com.baeldung.find.Person import org.junit.Test import static org.junit.Assert.* -class ListUnitTest { +class ListFindUnitTest { private final personList = [ new Person("Regina", "Fitzpatrick", 25), diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy similarity index 53% rename from core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy index 0d6bbed04b..16e231182b 100644 --- a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy @@ -1,11 +1,11 @@ -package com.baeldung.map +package com.baeldung.find -import com.baeldung.Person +import com.baeldung.find.Person import org.junit.Test import static org.junit.Assert.* -class MapUnitTest { +class MapFindUnitTest { private final personMap = [ Regina : new Person("Regina", "Fitzpatrick", 25), @@ -13,84 +13,6 @@ class MapUnitTest { Lucian : new Person("Lucian", "Walter", 30) ] - @Test - void whenUsingEach_thenMapIsIterated() { - def map = [ - 'FF0000' : 'Red', - '00FF00' : 'Lime', - '0000FF' : 'Blue', - 'FFFF00' : 'Yellow' - ] - - map.each { println "Hex Code: $it.key = Color Name: $it.value" } - } - - @Test - void whenUsingEachWithEntry_thenMapIsIterated() { - def map = [ - 'E6E6FA' : 'Lavender', - 'D8BFD8' : 'Thistle', - 'DDA0DD' : 'Plum', - ] - - map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" } - } - - @Test - void whenUsingEachWithKeyAndValue_thenMapIsIterated() { - def map = [ - '000000' : 'Black', - 'FFFFFF' : 'White', - '808080' : 'Gray' - ] - - map.each { key, val -> - println "Hex Code: $key = Color Name $val" - } - } - - @Test - void whenUsingEachWithIndexAndEntry_thenMapIsIterated() { - def map = [ - '800080' : 'Purple', - '4B0082' : 'Indigo', - '6A5ACD' : 'Slate Blue' - ] - - map.eachWithIndex { entry, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") - println "$indent Hex Code: $entry.key = Color Name: $entry.value" - } - } - - @Test - void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() { - def map = [ - 'FFA07A' : 'Light Salmon', - 'FF7F50' : 'Coral', - 'FF6347' : 'Tomato', - 'FF4500' : 'Orange Red' - ] - - map.eachWithIndex { key, val, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") - println "$indent Hex Code: $key = Color Name: $val" - } - } - - @Test - void whenUsingForLoop_thenMapIsIterated() { - def map = [ - '2E8B57' : 'Seagreen', - '228B22' : 'Forest Green', - '008000' : 'Green' - ] - - for (entry in map) { - println "Hex Code: $entry.key = Color Name: $entry.value" - } - } - @Test void whenMapContainsKeyElement_thenCheckReturnsTrue() { def map = [a: 'd', b: 'e', c: 'f'] diff --git a/core-groovy/src/main/groovy/com/baeldung/Person.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy similarity index 96% rename from core-groovy/src/main/groovy/com/baeldung/Person.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy index 6a009aeee0..e65826363a 100644 --- a/core-groovy/src/main/groovy/com/baeldung/Person.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy @@ -1,4 +1,4 @@ -package com.baeldung +package com.baeldung.find class Person { private String firstname diff --git a/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy similarity index 83% rename from core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy index 1248c9ac91..d2d03d5427 100644 --- a/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy @@ -1,10 +1,10 @@ -package com.baeldung.set +package com.baeldung.find import org.junit.Test import static org.junit.Assert.assertTrue -class SetUnitTest { +class SetFindUnitTest { @Test void whenSetContainsElement_thenCheckReturnsTrue() { diff --git a/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy new file mode 100644 index 0000000000..970203ce85 --- /dev/null +++ b/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy @@ -0,0 +1,87 @@ +package com.baeldung.iteratemap + +import com.baeldung.find.Person +import org.junit.Test + +import static org.junit.Assert.* + +class IterateMapUnitTest { + + @Test + void whenUsingEach_thenMapIsIterated() { + def map = [ + 'FF0000' : 'Red', + '00FF00' : 'Lime', + '0000FF' : 'Blue', + 'FFFF00' : 'Yellow' + ] + + map.each { println "Hex Code: $it.key = Color Name: $it.value" } + } + + @Test + void whenUsingEachWithEntry_thenMapIsIterated() { + def map = [ + 'E6E6FA' : 'Lavender', + 'D8BFD8' : 'Thistle', + 'DDA0DD' : 'Plum', + ] + + map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" } + } + + @Test + void whenUsingEachWithKeyAndValue_thenMapIsIterated() { + def map = [ + '000000' : 'Black', + 'FFFFFF' : 'White', + '808080' : 'Gray' + ] + + map.each { key, val -> + println "Hex Code: $key = Color Name $val" + } + } + + @Test + void whenUsingEachWithIndexAndEntry_thenMapIsIterated() { + def map = [ + '800080' : 'Purple', + '4B0082' : 'Indigo', + '6A5ACD' : 'Slate Blue' + ] + + map.eachWithIndex { entry, index -> + def indent = ((index == 0 || index % 2 == 0) ? " " : "") + println "$indent Hex Code: $entry.key = Color Name: $entry.value" + } + } + + @Test + void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() { + def map = [ + 'FFA07A' : 'Light Salmon', + 'FF7F50' : 'Coral', + 'FF6347' : 'Tomato', + 'FF4500' : 'Orange Red' + ] + + map.eachWithIndex { key, val, index -> + def indent = ((index == 0 || index % 2 == 0) ? " " : "") + println "$indent Hex Code: $key = Color Name: $val" + } + } + + @Test + void whenUsingForLoop_thenMapIsIterated() { + def map = [ + '2E8B57' : 'Seagreen', + '228B22' : 'Forest Green', + '008000' : 'Green' + ] + + for (entry in map) { + println "Hex Code: $entry.key = Color Name: $entry.value" + } + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy similarity index 98% rename from core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy index 7771028132..e4c0a0c177 100644 --- a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy @@ -1,9 +1,9 @@ -package com.baeldung.groovy.lists +package com.baeldung.lists import static groovy.test.GroovyAssert.* import org.junit.Test -class ListTest{ +class ListUnitTest { @Test void testCreateList() { diff --git a/core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy similarity index 99% rename from core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy index c6105eb1c4..deb552c420 100644 --- a/core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.maps; import static groovy.test.GroovyAssert.* import org.junit.Test diff --git a/core-groovy/README.md b/core-groovy/README.md index 0f45eed879..25a0aece3a 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -8,11 +8,8 @@ This module contains articles about core Groovy concepts - [Working with JSON in Groovy](https://www.baeldung.com/groovy-json) - [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) -- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) - [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits) - [Closures in Groovy](https://www.baeldung.com/groovy-closures) -- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements) -- [Lists in Groovy](https://www.baeldung.com/groovy-lists) - [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date) - [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io) - [[More -->]](/core-groovy-2) \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy b/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy deleted file mode 100644 index f1d528207f..0000000000 --- a/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy +++ /dev/null @@ -1,148 +0,0 @@ -package com.baeldung.groovy.map; - -import static groovy.test.GroovyAssert.* -import org.junit.Test - -class MapTest{ - - @Test - void createMap() { - - def emptyMap = [:] - assertNotNull(emptyMap) - - assertTrue(emptyMap instanceof java.util.LinkedHashMap) - - def map = [name:"Jerry", age: 42, city: "New York"] - assertTrue(map.size() == 3) - } - - @Test - void addItemsToMap() { - - def map = [name:"Jerry"] - - map["age"] = 42 - - map.city = "New York" - - def hobbyLiteral = "hobby" - def hobbyMap = [(hobbyLiteral): "Singing"] - map.putAll(hobbyMap) - - assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]) - assertTrue(hobbyMap.hobby == "Singing") - assertTrue(hobbyMap[hobbyLiteral] == "Singing") - - map.plus([1:20]) // returns new map - - map << [2:30] - - } - - @Test - void getItemsFromMap() { - - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - assertTrue(map["name"] == "Jerry") - - assertTrue(map.name == "Jerry") - - def propertyAge = "age" - assertTrue(map[propertyAge] == 42) - } - - @Test - void removeItemsFromMap() { - - def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49] - - def minusMap = map.minus([2:42, 4:34]); - assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49]) - - minusMap.removeAll{it -> it.key instanceof String} - assertTrue( minusMap == [ 1:20, 6:39, 7:49]) - - minusMap.retainAll{it -> it.value %2 == 0} - assertTrue( minusMap == [1:20]) - } - - @Test - void iteratingOnMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - map.each{ entry -> println "$entry.key: $entry.value" } - - map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" } - - map.eachWithIndex{ key, value, i -> println "$i $key: $value" } - } - - @Test - void filteringAndSearchingMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - assertTrue(map.find{ it.value == "New York"}.key == "city") - - assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"]) - - map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")} - - assertTrue(map.every{it -> it.value instanceof String} == false) - - assertTrue(map.any{it -> it.value instanceof String} == true) - } - - @Test - void collect(){ - - def map = [1: [name:"Jerry", age: 42, city: "New York"], - 2: [name:"Long", age: 25, city: "New York"], - 3: [name:"Dustin", age: 29, city: "New York"], - 4: [name:"Dustin", age: 34, city: "New York"]] - - def names = map.collect{entry -> entry.value.name} // returns only list - assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"]) - - def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name} - assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set) - - def idNames = map.collectEntries{key, value -> [key, value.name]} - assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"]) - - def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name} - assertTrue(below30Names == ["Long", "Dustin"]) - - - } - - @Test - void group(){ - def map = [1:20, 2: 40, 3: 11, 4: 93] - - def subMap = map.groupBy{it.value % 2} - println subMap - assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]]) - - def keySubMap = map.subMap([1, 2]) - assertTrue(keySubMap == [1:20, 2:40]) - - } - - @Test - void sorting(){ - def map = [ab:20, a: 40, cb: 11, ba: 93] - - def naturallyOrderedMap = map.sort() - assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap) - - def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator) - assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap) - - def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value }) - assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap) - - } - -} diff --git a/core-java-modules/README.md b/core-java-modules/README.md index 55dacca916..fa77846b45 100644 --- a/core-java-modules/README.md +++ b/core-java-modules/README.md @@ -5,6 +5,5 @@ This module contains modules about core Java ## Relevant articles: - [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) -- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel) - [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception) - [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) diff --git a/core-java-modules/core-java-9-improvements/README.md b/core-java-modules/core-java-9-improvements/README.md new file mode 100644 index 0000000000..b0baccba7f --- /dev/null +++ b/core-java-modules/core-java-9-improvements/README.md @@ -0,0 +1,17 @@ +## Core Java 9 + +This module contains articles about the improvements to core Java features introduced with Java 9. + +### Relevant Articles: + +- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) +- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional) +- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods) +- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api) +- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new) +- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture) + +#### Relevant articles not in this module: + +- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api) (see the [core-java-os](/core-java-os) module) + diff --git a/core-java-modules/core-java-9-improvements/pom.xml b/core-java-modules/core-java-9-improvements/pom.xml new file mode 100644 index 0000000000..aee289c79f --- /dev/null +++ b/core-java-modules/core-java-9-improvements/pom.xml @@ -0,0 +1,73 @@ + + 4.0.0 + core-java-9 + 0.2-SNAPSHOT + core-java-9 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + com.jayway.awaitility + awaitility + ${awaitility.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.google.guava + guava + ${guava.version} + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + core-java-9 + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + apache.snapshots + http://repository.apache.org/snapshots/ + + + + + + 3.10.0 + 1.2.0 + 1.7.0 + 1.9 + 1.9 + 25.1-jre + + + diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/Java9OptionalTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/Java9OptionalTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/Java9ObjectsAPIUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/collections/ListFactoryMethodsUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/collections/ListFactoryMethodsUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/collections/ListFactoryMethodsUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/collections/ListFactoryMethodsUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/collections/MapFactoryMethodsUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/collections/MapFactoryMethodsUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/collections/MapFactoryMethodsUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/collections/MapFactoryMethodsUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/collections/SetFactoryMethodsUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/collections/SetFactoryMethodsUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/collections/SetFactoryMethodsUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/collections/SetFactoryMethodsUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/stream/CollectorImprovementUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesUnitTest.java diff --git a/core-java-modules/core-java-9-jigsaw/README.md b/core-java-modules/core-java-9-jigsaw/README.md new file mode 100644 index 0000000000..b1a401d48c --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/README.md @@ -0,0 +1,11 @@ +## Core Java 9 + +This module contains articles about Project Jigsaw and the Java Platform Module System (JPMS), introduced with Java 9. + +### Relevant Articles: + +- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) +- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity) +- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api) + + diff --git a/core-java-modules/core-java-9/compile-simple-modules.sh b/core-java-modules/core-java-9-jigsaw/compile-simple-modules.sh similarity index 100% rename from core-java-modules/core-java-9/compile-simple-modules.sh rename to core-java-modules/core-java-9-jigsaw/compile-simple-modules.sh diff --git a/core-java-modules/core-java-9/compile-student-client.bat b/core-java-modules/core-java-9-jigsaw/compile-student-client.bat similarity index 100% rename from core-java-modules/core-java-9/compile-student-client.bat rename to core-java-modules/core-java-9-jigsaw/compile-student-client.bat diff --git a/core-java-modules/core-java-9/compile-student-model.bat b/core-java-modules/core-java-9-jigsaw/compile-student-model.bat similarity index 100% rename from core-java-modules/core-java-9/compile-student-model.bat rename to core-java-modules/core-java-9-jigsaw/compile-student-model.bat diff --git a/core-java-modules/core-java-9/compile-student-service-dbimpl.bat b/core-java-modules/core-java-9-jigsaw/compile-student-service-dbimpl.bat similarity index 100% rename from core-java-modules/core-java-9/compile-student-service-dbimpl.bat rename to core-java-modules/core-java-9-jigsaw/compile-student-service-dbimpl.bat diff --git a/core-java-modules/core-java-9/compile-student-service.bat b/core-java-modules/core-java-9-jigsaw/compile-student-service.bat similarity index 100% rename from core-java-modules/core-java-9/compile-student-service.bat rename to core-java-modules/core-java-9-jigsaw/compile-student-service.bat diff --git a/core-java-modules/core-java-9-jigsaw/pom.xml b/core-java-modules/core-java-9-jigsaw/pom.xml new file mode 100644 index 0000000000..8194ae9d00 --- /dev/null +++ b/core-java-modules/core-java-9-jigsaw/pom.xml @@ -0,0 +1,35 @@ + + 4.0.0 + core-java-9-jigsaw + 0.2-SNAPSHOT + core-java-9 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + core-java-9-jigsaw + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.9 + 1.9 + + + diff --git a/core-java-modules/core-java-9/run-simple-module-app.sh b/core-java-modules/core-java-9-jigsaw/run-simple-module-app.sh similarity index 100% rename from core-java-modules/core-java-9/run-simple-module-app.sh rename to core-java-modules/core-java-9-jigsaw/run-simple-module-app.sh diff --git a/core-java-modules/core-java-9/run-student-client.bat b/core-java-modules/core-java-9-jigsaw/run-student-client.bat similarity index 100% rename from core-java-modules/core-java-9/run-student-client.bat rename to core-java-modules/core-java-9-jigsaw/run-student-client.bat diff --git a/core-java-modules/core-java-9/run-student-client.sh b/core-java-modules/core-java-9-jigsaw/run-student-client.sh similarity index 100% rename from core-java-modules/core-java-9/run-student-client.sh rename to core-java-modules/core-java-9-jigsaw/run-student-client.sh diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.client/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.client/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.client/module-info.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.client/module-info.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.model/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.model/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.model/module-info.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.model/module-info.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.service.dbimpl/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service.dbimpl/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.service.dbimpl/module-info.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service.dbimpl/module-info.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.student.service/module-info.java b/core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.student.service/module-info.java rename to core-java-modules/core-java-9-jigsaw/src/modules/com.baeldung.student.service/module-info.java diff --git a/core-java-modules/core-java-9/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloInterface.java b/core-java-modules/core-java-9-jigsaw/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloInterface.java similarity index 100% rename from core-java-modules/core-java-9/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloInterface.java rename to core-java-modules/core-java-9-jigsaw/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloInterface.java diff --git a/core-java-modules/core-java-9/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloModules.java b/core-java-modules/core-java-9-jigsaw/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloModules.java similarity index 100% rename from core-java-modules/core-java-9/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloModules.java rename to core-java-modules/core-java-9-jigsaw/src/simple-modules/hello.modules/com/baeldung/modules/hello/HelloModules.java diff --git a/core-java-modules/core-java-9/src/simple-modules/hello.modules/module-info.java b/core-java-modules/core-java-9-jigsaw/src/simple-modules/hello.modules/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/simple-modules/hello.modules/module-info.java rename to core-java-modules/core-java-9-jigsaw/src/simple-modules/hello.modules/module-info.java diff --git a/core-java-modules/core-java-9/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java b/core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java similarity index 100% rename from core-java-modules/core-java-9/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java rename to core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/com/baeldung/modules/main/MainApp.java diff --git a/core-java-modules/core-java-9/src/simple-modules/main.app/module-info.java b/core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/simple-modules/main.app/module-info.java rename to core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/module-info.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java b/core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java rename to core-java-modules/core-java-9-jigsaw/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java diff --git a/core-java-modules/core-java-9-new-features/README.md b/core-java-modules/core-java-9-new-features/README.md new file mode 100644 index 0000000000..d547b9a221 --- /dev/null +++ b/core-java-modules/core-java-9-new-features/README.md @@ -0,0 +1,14 @@ +## Core Java 9 + +This module contains articles about core Java features that have been introduced in Java 9. + +### Relevant Articles: + +- [Java 9 New Features](https://www.baeldung.com/new-java-9) +- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles) +- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client) +- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) +- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation) +- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api) +- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) +- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams) diff --git a/core-java-modules/core-java-9/compile-aot.sh b/core-java-modules/core-java-9-new-features/compile-aot.sh similarity index 100% rename from core-java-modules/core-java-9/compile-aot.sh rename to core-java-modules/core-java-9-new-features/compile-aot.sh diff --git a/core-java-modules/core-java-9/compile-httpclient.bat b/core-java-modules/core-java-9-new-features/compile-httpclient.bat similarity index 100% rename from core-java-modules/core-java-9/compile-httpclient.bat rename to core-java-modules/core-java-9-new-features/compile-httpclient.bat diff --git a/core-java-modules/core-java-9/compile-modules.sh b/core-java-modules/core-java-9-new-features/compile-modules.sh similarity index 100% rename from core-java-modules/core-java-9/compile-modules.sh rename to core-java-modules/core-java-9-new-features/compile-modules.sh diff --git a/core-java-modules/core-java-9/logging.sh b/core-java-modules/core-java-9-new-features/logging.sh similarity index 100% rename from core-java-modules/core-java-9/logging.sh rename to core-java-modules/core-java-9-new-features/logging.sh diff --git a/core-java-modules/core-java-9/mods/logback.xml b/core-java-modules/core-java-9-new-features/mods/logback.xml similarity index 100% rename from core-java-modules/core-java-9/mods/logback.xml rename to core-java-modules/core-java-9-new-features/mods/logback.xml diff --git a/core-java-modules/core-java-9-new-features/pom.xml b/core-java-modules/core-java-9-new-features/pom.xml new file mode 100644 index 0000000000..cfdbb285d4 --- /dev/null +++ b/core-java-modules/core-java-9-new-features/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + core-java-9-new-features + 0.2-SNAPSHOT + core-java-9 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + core-java-9-new-features + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + apache.snapshots + http://repository.apache.org/snapshots/ + + + + + + 3.10.0 + 1.2.0 + 1.9 + 1.9 + + + diff --git a/core-java-modules/core-java-9/run-aot.sh b/core-java-modules/core-java-9-new-features/run-aot.sh similarity index 100% rename from core-java-modules/core-java-9/run-aot.sh rename to core-java-modules/core-java-9-new-features/run-aot.sh diff --git a/core-java-modules/core-java-9/run-httpclient.bat b/core-java-modules/core-java-9-new-features/run-httpclient.bat similarity index 100% rename from core-java-modules/core-java-9/run-httpclient.bat rename to core-java-modules/core-java-9-new-features/run-httpclient.bat diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/aot/JaotCompilation.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/aot/JaotCompilation.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/aot/JaotCompilation.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/aot/JaotCompilation.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/language/PrivateInterface.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/language/PrivateInterface.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImpl.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImpl.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImpl.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImpl.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungSubscriberImpl.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/reactive/BaeldungSubscriberImpl.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungSubscriberImpl.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/reactive/BaeldungSubscriberImpl.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/stackwalker/StackWalkerDemo.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/stackwalker/StackWalkerDemo.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/stackwalker/StackWalkerDemo.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/stackwalker/StackWalkerDemo.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/EndSubscriber.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/streams.reactive/EndSubscriber.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/EndSubscriber.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/streams.reactive/EndSubscriber.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/TransformProcessor.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/streams.reactive/TransformProcessor.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/streams.reactive/TransformProcessor.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/java9/streams.reactive/TransformProcessor.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/multireleaseapp/App.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/multireleaseapp/App.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/multireleaseapp/App.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/multireleaseapp/App.java diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/multireleaseapp/DateHelper.java b/core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/multireleaseapp/DateHelper.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/multireleaseapp/DateHelper.java rename to core-java-modules/core-java-9-new-features/src/main/java/com/baeldung/multireleaseapp/DateHelper.java diff --git a/core-java-modules/core-java-9/src/main/java9/com/baeldung/multireleaseapp/DateHelper.java b/core-java-modules/core-java-9-new-features/src/main/java9/com/baeldung/multireleaseapp/DateHelper.java similarity index 100% rename from core-java-modules/core-java-9/src/main/java9/com/baeldung/multireleaseapp/DateHelper.java rename to core-java-modules/core-java-9-new-features/src/main/java9/com/baeldung/multireleaseapp/DateHelper.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.httpclient/module-info.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.httpclient/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.httpclient/module-info.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.httpclient/module-info.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.app/module-info.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.app/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging.app/module-info.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.app/module-info.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.slf4j/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging.slf4j/module-info.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging/module-info.java b/core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging/module-info.java similarity index 100% rename from core-java-modules/core-java-9/src/modules/com.baeldung.logging/module-info.java rename to core-java-modules/core-java-9-new-features/src/modules/com.baeldung.logging/module-info.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageUnitTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/MultiResultionImageUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageUnitTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/MultiResultionImageUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamUnitTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/OptionalToStreamUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamUnitTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/OptionalToStreamUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/httpclient/HttpClientTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/httpclient/HttpClientTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/httpclient/HttpClientTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/httpclient/HttpClientTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/httpclient/HttpRequestTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/httpclient/HttpRequestTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/httpclient/HttpRequestTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/httpclient/HttpRequestTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/httpclient/HttpResponseTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/httpclient/HttpResponseTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/httpclient/HttpResponseTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/httpclient/HttpResponseTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/DiamondUnitTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/language/DiamondUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/DiamondUnitTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/language/DiamondUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceUnitTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/language/PrivateInterfaceUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceUnitTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/language/PrivateInterfaceUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesUnitTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/language/TryWithResourcesUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesUnitTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/language/TryWithResourcesUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImplIntegrationTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImplIntegrationTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImplIntegrationTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImplIntegrationTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/reactive/BaeldungSubscriberImplIntegrationTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/reactive/BaeldungSubscriberImplIntegrationTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/reactive/BaeldungSubscriberImplIntegrationTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/reactive/BaeldungSubscriberImplIntegrationTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/stackwalker/StackWalkerDemoUnitTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/stackwalker/StackWalkerDemoUnitTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/stackwalker/StackWalkerDemoUnitTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/stackwalker/StackWalkerDemoUnitTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/streams.reactive/ReactiveStreamsTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/streams.reactive/ReactiveStreamsTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/streams.reactive/ReactiveStreamsTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/streams.reactive/ReactiveStreamsTest.java diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java b/core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java similarity index 100% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java rename to core-java-modules/core-java-9-new-features/src/test/java/com/baeldung/java9/varhandles/VariableHandlesTest.java diff --git a/core-java-modules/core-java-9-streams/README.md b/core-java-modules/core-java-9-streams/README.md new file mode 100644 index 0000000000..0ad8500689 --- /dev/null +++ b/core-java-modules/core-java-9-streams/README.md @@ -0,0 +1,6 @@ +## Core Java 9 streams + +This module contains articles about Java 9 streams + +### Relevant Articles: +- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) diff --git a/core-java-modules/core-java-9-streams/pom.xml b/core-java-modules/core-java-9-streams/pom.xml new file mode 100644 index 0000000000..6e167caf9c --- /dev/null +++ b/core-java-modules/core-java-9-streams/pom.xml @@ -0,0 +1,31 @@ + + 4.0.0 + core-java-9-streams + 0.1.0-SNAPSHOT + core-java-9-streams + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + + core-java-9-streams + + + src/main/resources + true + + + + + + + diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomForEach.java b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomForEach.java similarity index 94% rename from java-streams-2/src/main/java/com/baeldung/breakforeach/CustomForEach.java rename to core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomForEach.java index 1f8866b16c..357571f092 100644 --- a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomForEach.java +++ b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomForEach.java @@ -1,4 +1,4 @@ -package com.baeldung.breakforeach; +package com.baeldung.streams.breakforeach; import java.util.Spliterator; import java.util.function.BiConsumer; diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomSpliterator.java b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomSpliterator.java similarity index 95% rename from java-streams-2/src/main/java/com/baeldung/breakforeach/CustomSpliterator.java rename to core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomSpliterator.java index cfe4bedac3..1844a3dc37 100644 --- a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomSpliterator.java +++ b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomSpliterator.java @@ -1,4 +1,4 @@ -package com.baeldung.breakforeach; +package com.baeldung.streams.breakforeach; import java.util.Spliterator; import java.util.Spliterators; diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomTakeWhile.java b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomTakeWhile.java similarity index 90% rename from java-streams-2/src/main/java/com/baeldung/breakforeach/CustomTakeWhile.java rename to core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomTakeWhile.java index 05574f9ae6..1852df3d9c 100644 --- a/java-streams-2/src/main/java/com/baeldung/breakforeach/CustomTakeWhile.java +++ b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/CustomTakeWhile.java @@ -1,4 +1,4 @@ -package com.baeldung.breakforeach; +package com.baeldung.streams.breakforeach; import java.util.function.Predicate; import java.util.stream.Stream; diff --git a/java-streams-2/src/main/java/com/baeldung/breakforeach/TakeWhileExample.java b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/TakeWhileExample.java similarity index 94% rename from java-streams-2/src/main/java/com/baeldung/breakforeach/TakeWhileExample.java rename to core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/TakeWhileExample.java index 1838ae5fb7..3a16c9d691 100644 --- a/java-streams-2/src/main/java/com/baeldung/breakforeach/TakeWhileExample.java +++ b/core-java-modules/core-java-9-streams/src/main/java/com/baeldung/streams/breakforeach/TakeWhileExample.java @@ -1,4 +1,4 @@ -package com.baeldung.breakforeach; +package com.baeldung.streams.breakforeach; import java.util.List; import java.util.stream.Stream; diff --git a/java-streams-2/src/test/java/com/baeldung/breakforeach/BreakFromStreamForEachUnitTest.java b/core-java-modules/core-java-9-streams/src/test/java/com/baeldung/streams/breakforeach/BreakFromStreamForEachUnitTest.java similarity index 96% rename from java-streams-2/src/test/java/com/baeldung/breakforeach/BreakFromStreamForEachUnitTest.java rename to core-java-modules/core-java-9-streams/src/test/java/com/baeldung/streams/breakforeach/BreakFromStreamForEachUnitTest.java index 23653c0a39..66d293b3fa 100644 --- a/java-streams-2/src/test/java/com/baeldung/breakforeach/BreakFromStreamForEachUnitTest.java +++ b/core-java-modules/core-java-9-streams/src/test/java/com/baeldung/streams/breakforeach/BreakFromStreamForEachUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.breakforeach; +package com.baeldung.streams.breakforeach; import org.junit.Test; diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md index f4939ae1e1..94f480db67 100644 --- a/core-java-modules/core-java-9/README.md +++ b/core-java-modules/core-java-9/README.md @@ -4,28 +4,13 @@ This module contains articles about Java 9 core features ### Relevant Articles: -- [Java 9 New Features](https://www.baeldung.com/new-java-9) -- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) -- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) -- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles) -- [Exploring the New HTTP Client in Java 9 and 11](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) - [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) - [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) -- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar) -- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation) -- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api) -- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new) -- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams) -- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional) -- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture) -- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api) -- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods) -- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api) -- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity) -- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api) -- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) - [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional) + +Note: also contains part of the code for the article +[How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering). diff --git a/core-java-modules/core-java-9/src/main/java/.gitignore b/core-java-modules/core-java-9/src/main/java/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/core-java-modules/core-java-9/src/main/java/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/README.MD b/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/README.MD deleted file mode 100644 index 2f44a2336b..0000000000 --- a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/README.MD +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Artiles: -- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional) diff --git a/core-java-modules/core-java-annotations/README.md b/core-java-modules/core-java-annotations/README.md index a125e8abd5..93da3aea62 100644 --- a/core-java-modules/core-java-annotations/README.md +++ b/core-java-modules/core-java-annotations/README.md @@ -8,4 +8,5 @@ - [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs) - [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated) - [Overview of Java Built-in Annotations](https://www.baeldung.com/java-default-annotations) -- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) \ No newline at end of file +- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) +- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency) diff --git a/core-java-modules/core-java-arrays-2/README.md b/core-java-modules/core-java-arrays-2/README.md index 5fa2f2bf4c..a78b3327b6 100644 --- a/core-java-modules/core-java-arrays-2/README.md +++ b/core-java-modules/core-java-arrays-2/README.md @@ -12,4 +12,5 @@ This module contains articles about Java arrays - [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) - [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element) - [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) +- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list) - [[<-- Prev]](/core-java-modules/core-java-arrays) diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md index 13ca191edb..de5daddb38 100644 --- a/core-java-modules/core-java-collections-2/README.md +++ b/core-java-modules/core-java-collections-2/README.md @@ -12,4 +12,4 @@ - [Sorting in Java](https://www.baeldung.com/java-sorting) - [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size) - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) - +- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) diff --git a/core-java-modules/core-java-collections-list-2/README.md b/core-java-modules/core-java-collections-list-2/README.md index fada9d96ac..0d2da41b41 100644 --- a/core-java-modules/core-java-collections-list-2/README.md +++ b/core-java-modules/core-java-collections-list-2/README.md @@ -11,4 +11,5 @@ This module contains articles about the Java List collection - [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list) - [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) - [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) -- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3) \ No newline at end of file +- [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist) +- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3) diff --git a/core-java-modules/core-java-date-operations/pom.xml b/core-java-modules/core-java-date-operations/pom.xml new file mode 100644 index 0000000000..f6e75ca518 --- /dev/null +++ b/core-java-modules/core-java-date-operations/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + core-java-date-operations + ${project.parent.version} + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java new file mode 100644 index 0000000000..ab1550fd90 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java @@ -0,0 +1,15 @@ +package com.baeldung.datetime; + +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; + +public class CalendarUtils { + + public static Calendar getPlusDays(Date date, int amount) throws ParseException { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.DAY_OF_YEAR, amount); + return calendar; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java new file mode 100644 index 0000000000..34f799d3f4 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java @@ -0,0 +1,20 @@ +package com.baeldung.datetime; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class DateUtils { + + public static Date getNow() { + return new Date(); + } + + public static Date getDate(long millis) { + return new Date(millis); + } + + public static Date getDate(String dateAsString, String pattern) throws ParseException { + return new SimpleDateFormat(pattern).parse(dateAsString); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java new file mode 100644 index 0000000000..1b4e825df8 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime.sql; + +import java.sql.Date; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class DateUtils { + + public static Date getNow() { + return new Date(System.currentTimeMillis()); + } + + public static Date getDate(String dateAsString) { + return Date.valueOf(dateAsString); + } + + public static Date getDate(String dateAsString, String pattern) throws ParseException { + java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString); + return new Date(customUtilDate.getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java new file mode 100644 index 0000000000..3fa1ffdef8 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime.sql; + +import java.sql.Time; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class TimeUtils { + + public static Time getNow() { + return new Time(System.currentTimeMillis()); + } + + public static Time getTime(String timeAsString) { + return Time.valueOf(timeAsString); + } + + public static Time getTime(String dateAsString, String pattern) throws ParseException { + java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString); + return new Time(customUtilDate.getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java new file mode 100644 index 0000000000..02a928daa7 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime.sql; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class TimestampUtils { + + public static Timestamp getNow() { + return new Timestamp(System.currentTimeMillis()); + } + + public static Timestamp getTimestamp(String timestampAsString) { + return Timestamp.valueOf(timestampAsString); + } + + public static Timestamp getTimestamp(String dateAsString, String pattern) throws ParseException { + java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString); + return new Timestamp(customUtilDate.getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java new file mode 100644 index 0000000000..0060162ffb --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.CalendarUtils; +import com.baeldung.datetime.DateUtils; + +import java.text.ParseException; +import java.util.Date; + +public class CalendarUtilsUnitTest { + + @Test + public void givenDateAndDaysToAdd_thenCalendarIsCorrectlyReturned() throws ParseException { + Date initialDate = DateUtils.getDate("2020/01/01", "yyyy/MM/dd"); + Date expectedDate= DateUtils.getDate("2020/01/11", "yyyy/MM/dd"); + assertEquals(expectedDate, CalendarUtils.getPlusDays(initialDate, 10).getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java new file mode 100644 index 0000000000..62a0fc0b4b --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.DateUtils; + +import java.text.ParseException; +import java.util.Date; + +public class DateUtilsUnitTest { + + @Test + public void givenTimeMillis_thenDateIsReturned() { + Date now = DateUtils.getNow(); + assertEquals(DateUtils.getDate(now.getTime()), now); + } + + @Test + public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { + long milliseconds = new Date(2020 - 1900, 0, 1).getTime(); + assertEquals(DateUtils.getDate(milliseconds), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java new file mode 100644 index 0000000000..a04f64f6dd --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.datetime.sql; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.sql.DateUtils; + +import java.text.ParseException; +import java.util.Date; + +public class DateUtilsUnitTest { + + @Test + public void givenCurrentDate_thenTodayIsReturned() { + assertEquals(DateUtils.getNow(), new Date()); + } + + @Test(expected = IllegalArgumentException.class) + public void givenDateAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + DateUtils.getDate("2020 01 01"); + } + + @Test + public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { + assertEquals(DateUtils.getDate("2020-01-01"), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java new file mode 100644 index 0000000000..6b49558f1b --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.datetime.sql; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.sql.TimeUtils; + +import java.text.ParseException; +import java.util.Date; + +public class TimeUtilsUnitTest { + + @Test + public void givenCurrentTime_thenNowIsReturned() { + assertEquals(TimeUtils.getNow(), new Date()); + } + + @Test(expected = IllegalArgumentException.class) + public void givenTimeAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + TimeUtils.getTime("10 11 12"); + } + + @Test + public void givenTimeAndPattern_thenTimeIsCorrectlyReturned() throws ParseException { + assertEquals(TimeUtils.getTime("10:11:12"), TimeUtils.getTime("10 11 12", "hh mm ss")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java new file mode 100644 index 0000000000..2faf8fab0e --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.datetime.sql; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.sql.TimestampUtils; + +import java.text.ParseException; +import java.util.Date; + +public class TimestampUtilsUnitTest { + + @Test + public void givenCurrentTimestamp_thenNowIsReturned() { + assertEquals(TimestampUtils.getNow() + .getTime(), new Date().getTime()); + } + + @Test(expected = IllegalArgumentException.class) + public void givenTimestampAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + TimestampUtils.getTimestamp("2020/01/01 10:11-12"); + } + + @Test + public void givenTimestampAndPattern_thenTimestampIsCorrectlyReturned() throws ParseException { + assertEquals(TimestampUtils.getTimestamp("2020-01-01 10:11:12"), TimestampUtils.getTimestamp("2020/01/01 10:11-12", "yyyy/MM/dd hh:mm-ss")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-computations/README.md b/core-java-modules/core-java-datetime-computations/README.md new file mode 100644 index 0000000000..591ddeaa94 --- /dev/null +++ b/core-java-modules/core-java-datetime-computations/README.md @@ -0,0 +1,15 @@ +## Java Date/time computations Cookbooks and Examples + +This module contains articles about date and time computations in Java. + +### Relevant Articles: +- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) +- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) +- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) +- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) +- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) +- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) +- [Calculate Age in Java](http://www.baeldung.com/java-get-age) +- [Increment Date in Java](http://www.baeldung.com/java-increment-date) +- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) +- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) diff --git a/core-java-modules/core-java-datetime-computations/pom.xml b/core-java-modules/core-java-datetime-computations/pom.xml new file mode 100644 index 0000000000..934df8018f --- /dev/null +++ b/core-java-modules/core-java-datetime-computations/pom.xml @@ -0,0 +1,71 @@ + + 4.0.0 + core-java-datetime-computations + ${project.parent.version} + core-java-datetime-computations + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + joda-time + joda-time + ${joda-time.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.darwinsys + hirondelle-date4j + RELEASE + test + + + + + core-java-datetime-computations + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 2.10 + + 3.6.1 + 1.9 + 1.9 + + diff --git a/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/AgeCalculator.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java diff --git a/java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java index a6cef94377..8b6d9885af 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java @@ -1,28 +1,28 @@ -package com.baeldung.datetime; - -import java.util.Calendar; -import java.util.Date; - -public class DateExtractYearMonthDayIntegerValues { - - int getYear(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - return calendar.get(Calendar.YEAR); - } - - int getMonth(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - return calendar.get(Calendar.MONTH); - } - - int getDay(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - return calendar.get(Calendar.DAY_OF_MONTH); - } -} +package com.baeldung.datetime; + +import java.util.Calendar; +import java.util.Date; + +public class DateExtractYearMonthDayIntegerValues { + + int getYear(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.YEAR); + } + + int getMonth(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.MONTH); + } + + int getDay(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.DAY_OF_MONTH); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java index b40e10f6ad..6daa86130d 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.LocalDate; - -public class LocalDateExtractYearMonthDayIntegerValues { - - int getYear(LocalDate localDate) { - return localDate.getYear(); - } - - int getMonth(LocalDate localDate) { - return localDate.getMonthValue(); - } - - int getDay(LocalDate localDate) { - return localDate.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.LocalDate; + +public class LocalDateExtractYearMonthDayIntegerValues { + + int getYear(LocalDate localDate) { + return localDate.getYear(); + } + + int getMonth(LocalDate localDate) { + return localDate.getMonthValue(); + } + + int getDay(LocalDate localDate) { + return localDate.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java index 404a62d2f4..bb4415fbc7 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.LocalDateTime; - -public class LocalDateTimeExtractYearMonthDayIntegerValues { - - int getYear(LocalDateTime localDateTime) { - return localDateTime.getYear(); - } - - int getMonth(LocalDateTime localDateTime) { - return localDateTime.getMonthValue(); - } - - int getDay(LocalDateTime localDateTime) { - return localDateTime.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.LocalDateTime; + +public class LocalDateTimeExtractYearMonthDayIntegerValues { + + int getYear(LocalDateTime localDateTime) { + return localDateTime.getYear(); + } + + int getMonth(LocalDateTime localDateTime) { + return localDateTime.getMonthValue(); + } + + int getDay(LocalDateTime localDateTime) { + return localDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java similarity index 96% rename from java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java index e686b05493..398c03102c 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.OffsetDateTime; - -public class OffsetDateTimeExtractYearMonthDayIntegerValues { - - int getYear(OffsetDateTime offsetDateTime) { - return offsetDateTime.getYear(); - } - - int getMonth(OffsetDateTime offsetDateTime) { - return offsetDateTime.getMonthValue(); - } - - int getDay(OffsetDateTime offsetDateTime) { - return offsetDateTime.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.OffsetDateTime; + +public class OffsetDateTimeExtractYearMonthDayIntegerValues { + + int getYear(OffsetDateTime offsetDateTime) { + return offsetDateTime.getYear(); + } + + int getMonth(OffsetDateTime offsetDateTime) { + return offsetDateTime.getMonthValue(); + } + + int getDay(OffsetDateTime offsetDateTime) { + return offsetDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java index 3e790b2b3f..86bce90f75 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.ZonedDateTime; - -public class ZonedDateTimeExtractYearMonthDayIntegerValues { - - int getYear(ZonedDateTime zonedDateTime) { - return zonedDateTime.getYear(); - } - - int getMonth(ZonedDateTime zonedDateTime) { - return zonedDateTime.getMonthValue(); - } - - int getDay(ZonedDateTime zonedDateTime) { - return zonedDateTime.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.ZonedDateTime; + +public class ZonedDateTimeExtractYearMonthDayIntegerValues { + + int getYear(ZonedDateTime zonedDateTime) { + return zonedDateTime.getYear(); + } + + int getMonth(ZonedDateTime zonedDateTime) { + return zonedDateTime.getMonthValue(); + } + + int getDay(ZonedDateTime zonedDateTime) { + return zonedDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java diff --git a/java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java diff --git a/java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java diff --git a/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateDiffUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateDiffUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateWithoutTimeUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/AddHoursToDateUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 96% rename from java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java index 3b1fcfa6c5..5914b5a727 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java +++ b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValuesUnitTest.java @@ -1,45 +1,45 @@ -package com.baeldung.datetime; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.junit.Before; -import org.junit.Test; - -public class DateExtractYearMonthDayIntegerValuesUnitTest { - - DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues(); - - Date date; - - @Before - public void setup() throws ParseException - { - date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018"); - } - - @Test - public void whenGetYear_thenCorrectYear() - { - int actualYear=extractYearMonthDateIntegerValues.getYear(date); - assertThat(actualYear,is(2018)); - } - - @Test - public void whenGetMonth_thenCorrectMonth() - { - int actualMonth=extractYearMonthDateIntegerValues.getMonth(date); - assertThat(actualMonth,is(02)); - } - - @Test - public void whenGetDay_thenCorrectDay() - { - int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date); - assertThat(actualDayOfMonth,is(01)); - } -} +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.junit.Before; +import org.junit.Test; + +public class DateExtractYearMonthDayIntegerValuesUnitTest { + + DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues(); + + Date date; + + @Before + public void setup() throws ParseException + { + date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018"); + } + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=extractYearMonthDateIntegerValues.getYear(date); + assertThat(actualYear,is(2018)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=extractYearMonthDateIntegerValues.getMonth(date); + assertThat(actualMonth,is(02)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date); + assertThat(actualDayOfMonth,is(01)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java similarity index 96% rename from java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java index 05de6ed0b9..641d45a536 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java +++ b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValuesUnitTest.java @@ -1,36 +1,36 @@ -package com.baeldung.datetime; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.time.LocalDate; - -import org.junit.Test; - -public class LocalDateExtractYearMonthDayIntegerValuesUnitTest { - - LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues(); - - LocalDate localDate=LocalDate.parse("2007-12-03"); - - @Test - public void whenGetYear_thenCorrectYear() - { - int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate); - assertThat(actualYear,is(2007)); - } - - @Test - public void whenGetMonth_thenCorrectMonth() - { - int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate); - assertThat(actualMonth,is(12)); - } - - @Test - public void whenGetDay_thenCorrectDay() - { - int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate); - assertThat(actualDayOfMonth,is(03)); - } -} +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.LocalDate; + +import org.junit.Test; + +public class LocalDateExtractYearMonthDayIntegerValuesUnitTest { + + LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues(); + + LocalDate localDate=LocalDate.parse("2007-12-03"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 96% rename from java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java index 70544ea970..295a4018c2 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java +++ b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest.java @@ -1,36 +1,36 @@ -package com.baeldung.datetime; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.time.LocalDateTime; - -import org.junit.Test; - -public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest { - - LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues(); - - LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30"); - - @Test - public void whenGetYear_thenCorrectYear() - { - int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime); - assertThat(actualYear,is(2007)); - } - - @Test - public void whenGetMonth_thenCorrectMonth() - { - int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime); - assertThat(actualMonth,is(12)); - } - - @Test - public void whenGetDay_thenCorrectDay() - { - int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime); - assertThat(actualDayOfMonth,is(03)); - } -} +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.LocalDateTime; + +import org.junit.Test; + +public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest { + + LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues(); + + LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 96% rename from java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java index efb01c49a5..3e1044e4be 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java +++ b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java @@ -1,36 +1,36 @@ -package com.baeldung.datetime; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.time.OffsetDateTime; - -import org.junit.Test; - -public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest { - - OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues(); - - OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00"); - - @Test - public void whenGetYear_thenCorrectYear() - { - int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime); - assertThat(actualYear,is(2007)); - } - - @Test - public void whenGetMonth_thenCorrectMonth() - { - int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime); - assertThat(actualMonth,is(12)); - } - - @Test - public void whenGetDay_thenCorrectDay() - { - int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime); - assertThat(actualDayOfMonth,is(03)); - } -} +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.OffsetDateTime; + +import org.junit.Test; + +public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest { + + OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues(); + + OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java similarity index 96% rename from java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java index a9ed3d2b74..2f2c0a99be 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java +++ b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest.java @@ -1,36 +1,36 @@ -package com.baeldung.datetime; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.time.ZonedDateTime; - -import org.junit.Test; - -public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest { - - ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues(); - - ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00"); - - @Test - public void whenGetYear_thenCorrectYear() - { - int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime); - assertThat(actualYear,is(2007)); - } - - @Test - public void whenGetMonth_thenCorrectMonth() - { - int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime); - assertThat(actualMonth,is(12)); - } - - @Test - public void whenGetDay_thenCorrectDay() - { - int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime); - assertThat(actualDayOfMonth,is(03)); - } -} +package com.baeldung.datetime; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.time.ZonedDateTime; + +import org.junit.Test; + +public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest { + + ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues(); + + ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00"); + + @Test + public void whenGetYear_thenCorrectYear() + { + int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime); + assertThat(actualYear,is(2007)); + } + + @Test + public void whenGetMonth_thenCorrectMonth() + { + int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime); + assertThat(actualMonth,is(12)); + } + + @Test + public void whenGetDay_thenCorrectDay() + { + int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime); + assertThat(actualDayOfMonth,is(03)); + } +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/datetime/modify/DateIncrementerUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/gregorian/calendar/GregorianCalendarTester.java diff --git a/java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/java9/time/TimeApiUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/README.md b/core-java-modules/core-java-datetime-java8/README.md new file mode 100644 index 0000000000..044f6f3fe3 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/README.md @@ -0,0 +1,15 @@ +## Java 8+ Date and Time API + +This module contains articles about the Date and Time API introduced with Java 8. + +### Relevant Articles: +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) +- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) +- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) +- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) +- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) +- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) +- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) +- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) +- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) +- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates) diff --git a/java-dates/pom.xml b/core-java-modules/core-java-datetime-java8/pom.xml similarity index 83% rename from java-dates/pom.xml rename to core-java-modules/core-java-datetime-java8/pom.xml index 761ebd71a6..72d51b5f10 100644 --- a/java-dates/pom.xml +++ b/core-java-modules/core-java-datetime-java8/pom.xml @@ -1,17 +1,16 @@ 4.0.0 - com.baeldung - java-dates - 0.1.0-SNAPSHOT - java-dates + core-java-datetime-java8 + ${project.parent.version} + core-java-datetime-java8 jar com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java @@ -21,11 +20,10 @@ ${commons-lang3.version} - log4j - log4j - ${log4j.version} + joda-time + joda-time + ${joda-time.version} - org.assertj assertj-core @@ -33,20 +31,15 @@ test - joda-time - joda-time - ${joda-time.version} - - - com.darwinsys - hirondelle-date4j - RELEASE + log4j + log4j + ${log4j.version} test - java-dates + core-java-datetime-java8 src/main/resources @@ -68,10 +61,10 @@ + 1.9 + 1.9 2.10 3.6.1 - 1.9 - 1.9 diff --git a/java-dates/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java diff --git a/java-dates/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UseDuration.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UsePeriod.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UseToInstant.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UseZonedDateTime.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java new file mode 100644 index 0000000000..3f965dbac7 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java @@ -0,0 +1,19 @@ +package com.baeldung.random; + +import java.util.Date; +import java.util.concurrent.ThreadLocalRandom; + +public class LegacyRandomDateTimes { + + public static Date between(Date startInclusive, Date endExclusive) { + long startMillis = startInclusive.getTime(); + long endMillis = endExclusive.getTime(); + long randomMillisSinceEpoch = ThreadLocalRandom.current().nextLong(startMillis, endMillis); + + return new Date(randomMillisSinceEpoch); + } + + public static Date timestamp() { + return new Date(ThreadLocalRandom.current().nextInt() * 1000L); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java new file mode 100644 index 0000000000..a40299e515 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java @@ -0,0 +1,27 @@ +package com.baeldung.random; + +import java.time.Instant; +import java.util.concurrent.ThreadLocalRandom; + +public class RandomDateTimes { + + public static Instant timestamp() { + return Instant.ofEpochSecond(ThreadLocalRandom.current().nextInt()); + } + + public static Instant between(Instant startInclusive, Instant endExclusive) { + long startSeconds = startInclusive.getEpochSecond(); + long endSeconds = endExclusive.getEpochSecond(); + long random = ThreadLocalRandom.current().nextLong(startSeconds, endSeconds); + + return Instant.ofEpochSecond(random); + } + + public static Instant after(Instant startInclusive) { + return between(startInclusive, Instant.MAX); + } + + public static Instant before(Instant upperExclusive) { + return between(Instant.MIN, upperExclusive); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java new file mode 100644 index 0000000000..f0b76873f9 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java @@ -0,0 +1,20 @@ +package com.baeldung.random; + +import java.time.LocalDate; +import java.util.concurrent.ThreadLocalRandom; + +public class RandomDates { + + public static LocalDate between(LocalDate startInclusive, LocalDate endExclusive) { + long startEpochDay = startInclusive.toEpochDay(); + long endEpochDay = endExclusive.toEpochDay(); + long randomDay = ThreadLocalRandom.current().nextLong(startEpochDay, endEpochDay); + + return LocalDate.ofEpochDay(randomDay); + } + + public static LocalDate date() { + int hundredYears = 100 * 365; + return LocalDate.ofEpochDay(ThreadLocalRandom.current().nextInt(-hundredYears, hundredYears)); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java new file mode 100644 index 0000000000..92818b2390 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java @@ -0,0 +1,19 @@ +package com.baeldung.random; + +import java.time.LocalTime; +import java.util.concurrent.ThreadLocalRandom; + +public class RandomTimes { + + public static LocalTime between(LocalTime startTime, LocalTime endTime) { + int startSeconds = startTime.toSecondOfDay(); + int endSeconds = endTime.toSecondOfDay(); + int randomTime = ThreadLocalRandom.current().nextInt(startSeconds, endSeconds); + + return LocalTime.ofSecondOfDay(randomTime); + } + + public static LocalTime time() { + return between(LocalTime.MIN, LocalTime.MAX); + } +} diff --git a/java-dates/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java diff --git a/java-dates/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java similarity index 97% rename from java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java index 4423ac6ce0..7e403ddcab 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java @@ -1,72 +1,72 @@ -package com.baeldung.datetime; - -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.junit.Assert; -import org.junit.Test; - -public class UseTimeZoneUnitTest { - - /* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ - - String timeZone = "Asia/Singapore"; - - private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a"; - - @Test - public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() { - Date nowUtc = new Date(); - TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone); - - Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore); - nowAsiaSingapore.setTime(nowUtc); - - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); - - System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone() - .getID(), simpleDateFormat.format(nowAsiaSingapore.getTime()))); - - Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond()); - Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone()); - - } - - @Test - public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() { - Instant nowUtc = Instant.now(); - ZoneId asiaSingapore = ZoneId.of(timeZone); - - ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore); - - System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), - nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN)))); - - Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond()); - Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); - } - - @Test - public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() { - org.joda.time.Instant nowUtc = org.joda.time.Instant.now(); - DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone); - - DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore); - - System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), - nowAsiaSingapore.toString(PATTERN))); - - Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis()); - Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); - } - -} +package com.baeldung.datetime; + +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.Assert; +import org.junit.Test; + +public class UseTimeZoneUnitTest { + + /* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ + + String timeZone = "Asia/Singapore"; + + private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a"; + + @Test + public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() { + Date nowUtc = new Date(); + TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone); + + Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore); + nowAsiaSingapore.setTime(nowUtc); + + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); + + System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone() + .getID(), simpleDateFormat.format(nowAsiaSingapore.getTime()))); + + Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond()); + Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone()); + + } + + @Test + public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() { + Instant nowUtc = Instant.now(); + ZoneId asiaSingapore = ZoneId.of(timeZone); + + ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore); + + System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), + nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN)))); + + Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond()); + Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); + } + + @Test + public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() { + org.joda.time.Instant nowUtc = org.joda.time.Instant.now(); + DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone); + + DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore); + + System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(), + nowAsiaSingapore.toString(PATTERN))); + + Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis()); + Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone()); + } + +} diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java new file mode 100644 index 0000000000..26fcaa942f --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.random; + +import org.junit.jupiter.api.RepeatedTest; + +import java.util.Date; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +class LegacyRandomDateTimesUnitTest { + + private static final Date MIN_DATE = new Date(Long.MIN_VALUE); + private static final Date MAX_DATE = new Date(Long.MAX_VALUE); + + @RepeatedTest(100) + void givenARange_WhenGenTimestamp_ShouldBeInRange() { + long aDay = TimeUnit.DAYS.toMillis(1); + long now = new Date().getTime(); + + Date hundredYearsAgo = new Date(now - aDay * 365 * 100); + Date tenDaysAgo = new Date(now - aDay * 10); + + Date random = LegacyRandomDateTimes.between(hundredYearsAgo, tenDaysAgo); + assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo); + } + + @RepeatedTest(100) + void givenNoRange_WhenGenTimestamp_ShouldGenerateRandomTimestamps() { + Date random = LegacyRandomDateTimes.timestamp(); + + assertThat(random) + .isNotNull() + .isBetween(MIN_DATE, MAX_DATE); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java new file mode 100644 index 0000000000..c801afa4e2 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.random; + +import org.junit.jupiter.api.RepeatedTest; + +import java.time.Duration; +import java.time.Instant; + +import static org.assertj.core.api.Assertions.assertThat; + +class RandomDateTimesUnitTest { + + @RepeatedTest(100) + void givenNoRange_WhenGenTimestamp_ShouldGenerateRandomTimestamps() { + Instant random = RandomDateTimes.timestamp(); + + assertThat(random).isBetween(Instant.MIN, Instant.MAX); + } + + @RepeatedTest(100) + void givenARange_WhenGenTimestamp_ShouldBeInRange() { + Instant hundredYearsAgo = Instant.now().minus(Duration.ofDays(100 * 365)); + Instant tenDaysAgo = Instant.now().minus(Duration.ofDays(10)); + + Instant random = RandomDateTimes.between(hundredYearsAgo, tenDaysAgo); + assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java new file mode 100644 index 0000000000..6005cf93c2 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.random; + +import org.junit.jupiter.api.RepeatedTest; + +import java.time.LocalDate; +import java.time.Month; + +import static org.assertj.core.api.Assertions.assertThat; + +class RandomDatesUnitTest { + + @RepeatedTest(100) + void givenNoRange_WhenGenDate_ShouldGenerateRandomDates() { + LocalDate randomDay = RandomDates.date(); + + assertThat(randomDay).isAfter(LocalDate.MIN).isBefore(LocalDate.MAX); + } + + @RepeatedTest(100) + void givenARange_WhenGenDate_ShouldBeInRange() { + LocalDate start = LocalDate.of(1989, Month.OCTOBER, 14); + LocalDate end = LocalDate.now(); + + LocalDate random = RandomDates.between(start, end); + assertThat(random).isAfter(start).isBefore(end); + } +} diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java new file mode 100644 index 0000000000..a346d0df20 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.random; + +import org.junit.jupiter.api.RepeatedTest; + +import java.time.LocalTime; + +import static org.assertj.core.api.Assertions.assertThat; + +class RandomTimesUnitTest { + + @RepeatedTest(100) + void givenARange_WhenGenTime_ShouldBeInRange() { + LocalTime morning = LocalTime.of(8, 30); + LocalTime randomTime = RandomTimes.between(LocalTime.MIDNIGHT, morning); + + assertThat(randomTime) + .isAfter(LocalTime.MIDNIGHT).isBefore(morning) + .isAfter(LocalTime.MIN).isBefore(LocalTime.MAX); + } +} diff --git a/java-dates/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index ba327b06f2..f7b0c37e73 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -12,4 +12,8 @@ This module contains articles about core java exceptions - [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws) - [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error) - [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions) - +- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) +- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler) +- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions) +- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) +- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java new file mode 100644 index 0000000000..fee52fe2bc --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java @@ -0,0 +1,16 @@ +package com.baeldung.trywithresource; + +public class AutoCloseableMain { + + public static void main(String[] args) throws Exception { + orderOfClosingResources(); + } + + private static void orderOfClosingResources() throws Exception { + try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); + AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { + af.doSomething(); + as.doSomething(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java new file mode 100644 index 0000000000..b001244d93 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java @@ -0,0 +1,17 @@ +package com.baeldung.trywithresource; + +public class AutoCloseableResourcesFirst implements AutoCloseable { + + public AutoCloseableResourcesFirst() { + System.out.println("Constructor -> AutoCloseableResources_First"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_First"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_First"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java new file mode 100644 index 0000000000..ef8bcd7166 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java @@ -0,0 +1,17 @@ +package com.baeldung.trywithresource; + +public class AutoCloseableResourcesSecond implements AutoCloseable { + + public AutoCloseableResourcesSecond() { + System.out.println("Constructor -> AutoCloseableResources_Second"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_Second"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_Second"); + } +} diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java new file mode 100644 index 0000000000..3ddf0f52e0 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java @@ -0,0 +1,8 @@ +package com.baeldung.trywithresource; + +public class MyResource implements AutoCloseable { + @Override + public void close() throws Exception { + System.out.println("Closed MyResource"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/README.md b/core-java-modules/core-java-io-2/README.md index 2299320f32..867b7ad732 100644 --- a/core-java-modules/core-java-io-2/README.md +++ b/core-java-modules/core-java-io-2/README.md @@ -3,4 +3,5 @@ - [Create a File in a Specific Directory in Java](https://www.baeldung.com/java-create-file-in-directory) - [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader) - +- [The Java File Class](https://www.baeldung.com/java-io-file) +- [Java FileWriter](https://www.baeldung.com/java-filewriter) diff --git a/core-java-modules/core-java-io-2/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java new file mode 100644 index 0000000000..8653b1e137 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java @@ -0,0 +1,96 @@ +package com.baeldung.scanner; + +import lombok.extern.log4j.Log4j; +import org.apache.log4j.LogManager; +import org.apache.log4j.PropertyConfigurator; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.Scanner; + +@Log4j +public class HasNextVsHasNextLineDemo { + private static final String LINE = "----------------------------"; + private static final String END_LINE = "--------OUTPUT--END---------\n"; + + + private static final String INPUT = new StringBuilder() + .append("magic\tproject\n") + .append(" database: oracle\n") + .append("dependencies:\n") + .append("spring:foo:bar\n") + .append("\n").toString(); + + private static void hasNextBasic() { + printHeader("hasNext() Basic"); + Scanner scanner = new Scanner(INPUT); + while (scanner.hasNext()) { + log.info(scanner.next()); + } + log.info(END_LINE); + scanner.close(); + } + + private static void hasNextWithDelimiter() { + printHeader("hasNext() with delimiter"); + Scanner scanner = new Scanner(INPUT); + while (scanner.hasNext()) { + String token = scanner.next(); + if ("dependencies:".equals(token)) { + scanner.useDelimiter(":"); + } + log.info(token); + } + log.info(END_LINE); + scanner.close(); + } + + private static void hasNextWithDelimiterFixed() { + printHeader("hasNext() with delimiter FIX"); + Scanner scanner = new Scanner(INPUT); + while (scanner.hasNext()) { + String token = scanner.next(); + if ("dependencies:".equals(token)) { + scanner.useDelimiter(":|\\s+"); + } + log.info(token); + } + log.info(END_LINE); + scanner.close(); + } + + private static void addLineNumber() { + printHeader("add line number by hasNextLine() "); + Scanner scanner = new Scanner(INPUT); + int i = 0; + while (scanner.hasNextLine()) { + log.info(String.format("%d|%s", ++i, scanner.nextLine())); + } + log.info(END_LINE); + scanner.close(); + } + + private static void printHeader(String title) { + log.info(LINE); + log.info(title); + log.info(LINE); + } + + public static void main(String[] args) throws IOException { + setLogger(); + hasNextBasic(); + hasNextWithDelimiter(); + hasNextWithDelimiterFixed(); + addLineNumber(); + } + + //overwrite the logger config + private static void setLogger() throws IOException { + InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties"); + Properties props = new Properties(); + props.load(is); + LogManager.resetConfiguration(); + PropertyConfigurator.configure(props); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/src/main/resources/scanner/log4j.properties b/core-java-modules/core-java-io-2/src/main/resources/scanner/log4j.properties new file mode 100644 index 0000000000..59cb116bff --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/resources/scanner/log4j.properties @@ -0,0 +1,4 @@ +log4j.rootLogger=INFO, A1 +log4j.appender.A1=org.apache.log4j.ConsoleAppender +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=[DEMO]%m%n diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java new file mode 100644 index 0000000000..471c0ea1c7 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.scanner; + +import static org.junit.Assert.assertEquals; + +import java.util.NoSuchElementException; +import java.util.Scanner; + +import org.junit.Test; + +public class JavaScannerUnitTest { + + @Test + public void whenReadingLines_thenCorrect() { + String input = "Scanner\nTest\n"; + try (Scanner scanner = new Scanner(input)) { + assertEquals("Scanner", scanner.nextLine()); + assertEquals("Test", scanner.nextLine()); + } + } + + @Test + public void whenReadingPartialLines_thenCorrect() { + String input = "Scanner\n"; + try (Scanner scanner = new Scanner(input)) { + scanner.useDelimiter(""); + scanner.next(); + assertEquals("canner", scanner.nextLine()); + } + } + + @Test(expected = NoSuchElementException.class) + public void givenNoNewLine_whenReadingNextLine_thenThrowNoSuchElementException() { + try (Scanner scanner = new Scanner("")) { + String result = scanner.nextLine(); + } + } + + @Test(expected = IllegalStateException.class) + public void givenScannerIsClosed_whenReadingNextLine_thenThrowIllegalStateException() { + Scanner scanner = new Scanner(""); + scanner.close(); + String result = scanner.nextLine(); + } +} diff --git a/core-java-modules/core-java-io/README.md b/core-java-modules/core-java-io/README.md index 34b2f371e1..2a68e861e8 100644 --- a/core-java-modules/core-java-io/README.md +++ b/core-java-modules/core-java-io/README.md @@ -13,22 +13,11 @@ This module contains articles about core Java input and output (IO) - [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library) - [File Size in Java](http://www.baeldung.com/java-file-size) - [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path) -- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer) - [How to Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file) - [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception) - [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java) -- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel) -- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor) -- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) -- [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) -- [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) -- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) -- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) -- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) -- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink) - [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter) - [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist) - [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream) @@ -40,6 +29,5 @@ This module contains articles about core Java input and output (IO) - [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv) - [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files) - [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) -- [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector) - [How to Avoid the Java FileNotFoundException When Loading Resources](https://www.baeldung.com/java-classpath-resource-cannot-be-opened) - [[More -->]](/core-java-modules/core-java-io-2) diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index c3c48ba679..393ab5e318 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -27,12 +27,6 @@ ${hsqldb.version} runtime - - - org.asynchttpclient - async-http-client - ${async-http-client.version} - com.opencsv opencsv @@ -50,6 +44,12 @@ jmimemagic ${jmime-magic.version} + + + com.sun.messaging.mq + fscontext + ${fscontext.version} + @@ -149,12 +149,11 @@ 3.0.0-M1 2.4.0 - 2.4.5 1.18 0.1.5 3.1.0 - + 4.4.2 \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/README.md b/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/README.md deleted file mode 100644 index b28aae1397..0000000000 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/README.md +++ /dev/null @@ -1,2 +0,0 @@ -###Relevant Articles: -- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector) diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/filechannel/FileChannelUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/filechannel/FileChannelUnitTest.java deleted file mode 100644 index 6964ba80e3..0000000000 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/filechannel/FileChannelUnitTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.baeldung.filechannel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.charset.StandardCharsets; - -import org.junit.Test; - -public class FileChannelUnitTest { - - @Test - public void givenFile_whenReadWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException { - - try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); - FileChannel channel = reader.getChannel(); - ByteArrayOutputStream out = new ByteArrayOutputStream();) { - - int bufferSize = 1024; - if (bufferSize > channel.size()) { - bufferSize = (int) channel.size(); - } - ByteBuffer buff = ByteBuffer.allocate(bufferSize); - - while (channel.read(buff) > 0) { - out.write(buff.array(), 0, buff.position()); - buff.clear(); - } - - String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8); - - assertEquals("Hello world", fileContent); - } - } - - @Test - public void givenFile_whenReadWithFileChannelUsingFileInputStream_thenCorrect() throws IOException { - - try (ByteArrayOutputStream out = new ByteArrayOutputStream(); - FileInputStream fin = new FileInputStream("src/test/resources/test_read.in"); - FileChannel channel = fin.getChannel();) { - - int bufferSize = 1024; - if (bufferSize > channel.size()) { - bufferSize = (int) channel.size(); - } - ByteBuffer buff = ByteBuffer.allocate(bufferSize); - - while (channel.read(buff) > 0) { - out.write(buff.array(), 0, buff.position()); - buff.clear(); - } - String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8); - - assertEquals("Hello world", fileContent); - } - } - - @Test - public void givenFile_whenReadAFileSectionIntoMemoryWithFileChannel_thenCorrect() throws IOException { - - try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); - FileChannel channel = reader.getChannel(); - ByteArrayOutputStream out = new ByteArrayOutputStream();) { - - MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 6, 5); - - if (buff.hasRemaining()) { - byte[] data = new byte[buff.remaining()]; - buff.get(data); - assertEquals("world", new String(data, StandardCharsets.UTF_8)); - } - } - } - - @Test - public void whenWriteWithFileChannelUsingRandomAccessFile_thenCorrect() throws IOException { - String file = "src/test/resources/test_write_using_filechannel.txt"; - try (RandomAccessFile writer = new RandomAccessFile(file, "rw"); - FileChannel channel = writer.getChannel();) { - ByteBuffer buff = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8)); - - channel.write(buff); - - // now we verify whether the file was written correctly - RandomAccessFile reader = new RandomAccessFile(file, "r"); - assertEquals("Hello world", reader.readLine()); - reader.close(); - } - } - - @Test - public void givenFile_whenWriteAFileUsingLockAFileSectionWithFileChannel_thenCorrect() throws IOException { - try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "rw"); - FileChannel channel = reader.getChannel(); - FileLock fileLock = channel.tryLock(6, 5, Boolean.FALSE);) { - - assertNotNull(fileLock); - } - } - - @Test - public void givenFile_whenReadWithFileChannelGetPosition_thenCorrect() throws IOException { - - try (ByteArrayOutputStream out = new ByteArrayOutputStream(); - RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); - FileChannel channel = reader.getChannel();) { - - int bufferSize = 1024; - if (bufferSize > channel.size()) { - bufferSize = (int) channel.size(); - } - ByteBuffer buff = ByteBuffer.allocate(bufferSize); - - while (channel.read(buff) > 0) { - out.write(buff.array(), 0, buff.position()); - buff.clear(); - } - - // the original file is 11 bytes long, so that's where the position pointer should be - assertEquals(11, channel.position()); - - channel.position(4); - assertEquals(4, channel.position()); - } - } - - @Test - public void whenGetFileSize_thenCorrect() throws IOException { - - try (RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r"); - FileChannel channel = reader.getChannel();) { - - // the original file is 11 bytes long, so that's where the position pointer should be - assertEquals(11, channel.size()); - } - } - - @Test - public void whenTruncateFile_thenCorrect() throws IOException { - String input = "this is a test input"; - - FileOutputStream fout = new FileOutputStream("src/test/resources/test_truncate.txt"); - FileChannel channel = fout.getChannel(); - - ByteBuffer buff = ByteBuffer.wrap(input.getBytes()); - channel.write(buff); - buff.flip(); - - channel = channel.truncate(5); - assertEquals(5, channel.size()); - - fout.close(); - channel.close(); - } -} diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/README.md b/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/README.md deleted file mode 100644 index 569be82d27..0000000000 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/README.md +++ /dev/null @@ -1,11 +0,0 @@ -### Relevant Articles: -- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) -- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path) -- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel) -- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) -- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) -- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor) -- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) -- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) -- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) -- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) diff --git a/core-java-modules/core-java-io/src/test/resources/test_truncate.txt b/core-java-modules/core-java-io/src/test/resources/test_truncate.txt deleted file mode 100644 index 26d3b38cdd..0000000000 --- a/core-java-modules/core-java-io/src/test/resources/test_truncate.txt +++ /dev/null @@ -1 +0,0 @@ -this \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/test/resources/test_write_using_filechannel.txt b/core-java-modules/core-java-io/src/test/resources/test_write_using_filechannel.txt deleted file mode 100644 index 70c379b63f..0000000000 --- a/core-java-modules/core-java-io/src/test/resources/test_write_using_filechannel.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world \ No newline at end of file diff --git a/core-java-modules/core-java-jvm/README.md b/core-java-modules/core-java-jvm/README.md index a1a57c83c5..89600ad924 100644 --- a/core-java-modules/core-java-jvm/README.md +++ b/core-java-modules/core-java-jvm/README.md @@ -1,8 +1,12 @@ -========= - ## Core Java JVM Cookbooks and Examples +This module contains articles about working with the Java Virtual Machine (JVM). + ### Relevant Articles: + - [Method Inlining in the JVM](https://www.baeldung.com/jvm-method-inlining) +- [JVM Log Forging](https://www.baeldung.com/jvm-log-forging) +- [Guide to Java Instrumentation](https://www.baeldung.com/java-instrumentation) +- [Class Loaders in Java](https://www.baeldung.com/java-classloaders) - [A Guide to System.exit()](https://www.baeldung.com/java-system-exit) - [Guide to System.gc()](https://www.baeldung.com/java-system-gc) diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 8e8271f09b..74960820d7 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -13,4 +13,49 @@ ../../ + + + junit + junit + ${junit.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.javassist + javassist + ${javaassist.version} + + + org.owasp.esapi + esapi + ${esapi.version} + + + com.sun + tools + ${sun.tools.version} + system + ${java.home}/../lib/tools.jar + + + + + + 3.6.1 + + 3.21.0-GA + 2.1.0.1 + 1.8.0 + diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/CustomClassLoader.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/CustomClassLoader.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/classloader/PrintClassLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/classloader/PrintClassLoader.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/Launcher.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/Launcher.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtm.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtm.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/logforging/LogForgingDemo.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/logforging/LogForgingDemo.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/logforging/LogForgingDemo.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/logforging/LogForgingDemo.java diff --git a/core-java-modules/core-java/src/main/resources/ESAPI.properties b/core-java-modules/core-java-jvm/src/main/resources/ESAPI.properties similarity index 100% rename from core-java-modules/core-java/src/main/resources/ESAPI.properties rename to core-java-modules/core-java-jvm/src/main/resources/ESAPI.properties diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-3/README.md b/core-java-modules/core-java-lang-oop-3/README.md index 4ac6c3ffe9..69fb4f5d28 100644 --- a/core-java-modules/core-java-lang-oop-3/README.md +++ b/core-java-modules/core-java-lang-oop-3/README.md @@ -7,11 +7,12 @@ This module contains articles about Object-oriented programming (OOP) in Java - [Access Modifiers in Java](https://www.baeldung.com/java-access-modifiers) - [Guide to the super Java Keyword](https://www.baeldung.com/java-super) - [Guide to the this Java Keyword](https://www.baeldung.com/java-this) -- [Java Public Access Modifier](https://www.baeldung.com/java-public-keyword) +- [Java ‘public’ Access Modifier](https://www.baeldung.com/java-public-keyword) - [Composition, Aggregation and Association in Java](https://www.baeldung.com/java-composition-aggregation-association) - [Nested Classes in Java](https://www.baeldung.com/java-nested-classes) - [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces) - [Java Classes and Objects](https://www.baeldung.com/java-classes-objects) - [Java Interfaces](https://www.baeldung.com/java-interfaces) - [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding) -- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2) \ No newline at end of file +- [Methods in Java](https://www.baeldung.com/java-methods) +- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2) [[More -->]](/core-java-modules/core-java-lang-oop-4) diff --git a/core-java-modules/core-java-lang-oop-4/README.md b/core-java-modules/core-java-lang-oop-4/README.md new file mode 100644 index 0000000000..fae5b3091b --- /dev/null +++ b/core-java-modules/core-java-lang-oop-4/README.md @@ -0,0 +1,6 @@ +## Core Java Lang OOP (Part 4) + +This module contains articles about Object-oriented programming (OOP) in Java + +### Relevant Articles: +- [[<-- Prev]](/core-java-modules/core-java-lang-oop-3) diff --git a/core-java-modules/core-java-lang-oop-4/pom.xml b/core-java-modules/core-java-lang-oop-4/pom.xml new file mode 100644 index 0000000000..72662a8ea4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-4/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + core-java-lang-oop-4 + 0.1.0-SNAPSHOT + core-java-lang-oop-4 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + test + + + + + core-java-lang-oop-4 + + + src/main/resources + true + + + + + + 3.10.0 + + + diff --git a/core-java-modules/core-java-lang-syntax-2/README.md b/core-java-modules/core-java-lang-syntax-2/README.md index a3b11865af..538a29181a 100644 --- a/core-java-modules/core-java-lang-syntax-2/README.md +++ b/core-java-modules/core-java-lang-syntax-2/README.md @@ -11,4 +11,5 @@ This module contains articles about Java syntax - [Java Double Brace Initialization](https://www.baeldung.com/java-double-brace-initialization) - [The Java Native Keyword and Methods](https://www.baeldung.com/java-native) - [Variable Scope in Java](https://www.baeldung.com/java-variable-scope) +- [Java ‘protected’ Access Modifier](https://www.baeldung.com/java-protected-access-modifier) - [[<-- Prev]](/core-java-modules/core-java-lang-syntax) diff --git a/core-java-modules/core-java-lang/README.md b/core-java-modules/core-java-lang/README.md index 9b485d80e9..9e98bb849b 100644 --- a/core-java-modules/core-java-lang/README.md +++ b/core-java-modules/core-java-lang/README.md @@ -13,4 +13,7 @@ This module contains articles about core features in the Java language - [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic) - [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) -- [[More --> ]](/core-java-modules/core-java-lang-2) \ No newline at end of file +- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break) +- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) +- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java) +- [[More --> ]](/core-java-modules/core-java-lang-2) diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md index c384a28b64..120b111ff5 100644 --- a/core-java-modules/core-java-networking-2/README.md +++ b/core-java-modules/core-java-networking-2/README.md @@ -4,9 +4,11 @@ This module contains articles about networking in Java ### Relevant Articles -- [Checking if a URL Exists in Java](https://www.baeldung.com/java-check-url-exists) -- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post) +- [Checking If a URL Exists in Java](https://www.baeldung.com/java-check-url-exists) +- [Making a JSON POST Request with HttpURLConnection](https://www.baeldung.com/httpurlconnection-post) - [Using Curl in Java](https://www.baeldung.com/java-curl) -- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) -- [Sending Emails with Java](http://www.baeldung.com/java-email) +- [Do a Simple HTTP Request in Java](https://www.baeldung.com/java-http-request) +- [Sending Emails with Java](https://www.baeldung.com/java-email) +- [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection) +- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file) - [[<-- Prev]](/core-java-modules/core-java-networking) diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml index 2d404a553b..c3a5891066 100644 --- a/core-java-modules/core-java-networking-2/pom.xml +++ b/core-java-modules/core-java-networking-2/pom.xml @@ -6,9 +6,10 @@ jar - com.baeldung.core-java-modules - core-java-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java @@ -27,6 +28,11 @@ mail ${javax.mail.version} + + org.asynchttpclient + async-http-client + ${async-http-client.version} + @@ -36,5 +42,6 @@ 4.5.9 1.5.0-b01 + 2.4.5 diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/download/FileDownload.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/download/FileDownload.java similarity index 99% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/download/FileDownload.java rename to core-java-modules/core-java-networking-2/src/main/java/com/baeldung/download/FileDownload.java index a099406d4c..ebcf7a70f7 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/download/FileDownload.java +++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/download/FileDownload.java @@ -4,7 +4,7 @@ import org.apache.commons.io.FileUtils; import org.asynchttpclient.*; import java.io.*; -import java.net.*; +import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/download/ResumableDownload.java similarity index 100% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java rename to core-java-modules/core-java-networking-2/src/main/java/com/baeldung/download/ResumableDownload.java diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java similarity index 98% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java rename to core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java index 81ac391958..16017ee482 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java +++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java @@ -1,8 +1,10 @@ package com.baeldung.download; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; +import javax.xml.bind.DatatypeConverter; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; @@ -11,11 +13,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.concurrent.ExecutionException; -import javax.xml.bind.DatatypeConverter; - -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.Assert.assertTrue; public class FileDownloadIntegrationTest { diff --git a/core-java-modules/core-java-nio-2/README.md b/core-java-modules/core-java-nio-2/README.md new file mode 100644 index 0000000000..8b29c97385 --- /dev/null +++ b/core-java-modules/core-java-nio-2/README.md @@ -0,0 +1,11 @@ +## Core Java NIO + +This module contains articles about core Java non-blocking input and output (IO) + +## Relevant Articles: + +- [A Guide to WatchService in Java NIO2](https://www.baeldung.com/java-nio2-watchservice) +- [Create a Symbolic Link with Java](https://www.baeldung.com/java-symlink) +- [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector) +- [Using Java MappedByteBuffer](https://www.baeldung.com/java-mapped-byte-buffer) +- [[<-- Prev]](/core-java-modules/core-java-nio) \ No newline at end of file diff --git a/core-java-modules/core-java-nio-2/pom.xml b/core-java-modules/core-java-nio-2/pom.xml new file mode 100644 index 0000000000..c1fa423b38 --- /dev/null +++ b/core-java-modules/core-java-nio-2/pom.xml @@ -0,0 +1,17 @@ + + 4.0.0 + core-java-nio-2 + 0.1.0-SNAPSHOT + core-java-nio-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoClient.java similarity index 96% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/EchoClient.java rename to core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoClient.java index 61f339db58..dd0a15ac7e 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/EchoClient.java +++ b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio.selector; +package com.baeldung.selector; import java.io.IOException; import java.net.InetSocketAddress; diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java similarity index 98% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/EchoServer.java rename to core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java index 7c1e291646..8cf2e941fe 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio/selector/EchoServer.java +++ b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio.selector; +package com.baeldung.selector; import java.io.File; import java.io.IOException; diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/symlink/SymLinkExample.java b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/symlink/SymLinkExample.java similarity index 93% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/symlink/SymLinkExample.java rename to core-java-modules/core-java-nio-2/src/main/java/com/baeldung/symlink/SymLinkExample.java index 63ee0f14b1..4c2c47e085 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/symlink/SymLinkExample.java +++ b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/symlink/SymLinkExample.java @@ -6,9 +6,11 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import static java.nio.file.StandardOpenOption.*; import java.util.stream.IntStream; +import static java.nio.file.StandardOpenOption.CREATE; +import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; + public class SymLinkExample { public void createSymbolicLink(Path link, Path target) throws IOException { diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/watcher/DirectoryWatcherExample.java similarity index 74% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java rename to core-java-modules/core-java-nio-2/src/main/java/com/baeldung/watcher/DirectoryWatcherExample.java index 4c35ffdb22..e8a2a401ab 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java +++ b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/watcher/DirectoryWatcherExample.java @@ -1,13 +1,7 @@ -package com.baeldung.java.nio2.watcher; +package com.baeldung.watcher; import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardWatchEventKinds; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; +import java.nio.file.*; public class DirectoryWatcherExample { diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java similarity index 100% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java rename to core-java-modules/core-java-nio-2/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio/selector/NioEchoLiveTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/selector/NioEchoLiveTest.java similarity index 87% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio/selector/NioEchoLiveTest.java rename to core-java-modules/core-java-nio-2/src/test/java/com/baeldung/selector/NioEchoLiveTest.java index 0e1afa87a5..39deb798e5 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio/selector/NioEchoLiveTest.java +++ b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/selector/NioEchoLiveTest.java @@ -1,13 +1,15 @@ -package com.baeldung.java.nio.selector; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; +package com.baeldung.selector; +import com.baeldung.selector.EchoClient; +import com.baeldung.selector.EchoServer; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + public class NioEchoLiveTest { private Process server; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java similarity index 100% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java rename to core-java-modules/core-java-nio-2/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java index caa7049475..e6723e719c 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java +++ b/core-java-modules/core-java-nio-2/src/test/java/com/baeldung/symlink/SymLinkExampleManualTest.java @@ -1,13 +1,13 @@ package com.baeldung.symlink; -import static org.junit.Assert.*; +import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import org.junit.Test; +import static org.junit.Assert.*; public class SymLinkExampleManualTest { diff --git a/core-java-modules/core-java-io/src/test/resources/fileToRead.txt b/core-java-modules/core-java-nio-2/src/test/resources/fileToRead.txt similarity index 100% rename from core-java-modules/core-java-io/src/test/resources/fileToRead.txt rename to core-java-modules/core-java-nio-2/src/test/resources/fileToRead.txt diff --git a/core-java-modules/core-java-io/src/test/resources/fileToWriteTo.txt b/core-java-modules/core-java-nio-2/src/test/resources/fileToWriteTo.txt similarity index 100% rename from core-java-modules/core-java-io/src/test/resources/fileToWriteTo.txt rename to core-java-modules/core-java-nio-2/src/test/resources/fileToWriteTo.txt diff --git a/core-java-modules/core-java-nio/README.md b/core-java-modules/core-java-nio/README.md index 727bd2546c..f37c8a3d38 100644 --- a/core-java-modules/core-java-nio/README.md +++ b/core-java-modules/core-java-nio/README.md @@ -5,4 +5,13 @@ This module contains articles about core Java non-blocking input and output (IO) ## Relevant Articles: - [Determine File Creation Date in Java](https://www.baeldung.com/java-file-creation-date) -- [Find the Number of Lines in a File Using Jav](https://www.baeldung.com/java-file-number-of-lines) +- [Find the Number of Lines in a File Using Java](https://www.baeldung.com/java-file-number-of-lines) +- [A Guide to NIO2 Asynchronous File Channel](https://www.baeldung.com/java-nio2-async-file-channel) +- [A Guide to NIO2 FileVisitor](https://www.baeldung.com/java-nio2-file-visitor) +- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel) +- [A Guide to NIO2 File Attribute APIs](https://www.baeldung.com/java-nio2-file-attribute) +- [Introduction to the Java NIO2 File API](https://www.baeldung.com/java-nio-2-file-api) +- [Java NIO2 Path API](https://www.baeldung.com/java-nio-2-path) +- [Guide to Java NIO2 Asynchronous Channel APIs](https://www.baeldung.com/java-nio-2-async-channels) +- [A Guide to NIO2 Asynchronous Socket Channel](https://www.baeldung.com/java-nio2-async-socket-channel) +- [[More -->]](/core-java-modules/core-java-nio-2) \ No newline at end of file diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml index 31433e632f..da8759a956 100644 --- a/core-java-modules/core-java-nio/pom.xml +++ b/core-java-modules/core-java-nio/pom.xml @@ -13,4 +13,5 @@ 0.0.1-SNAPSHOT ../../parent-java + \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java b/core-java-modules/core-java-nio/src/main/java/com/baeldung/filevisitor/FileSearchExample.java similarity index 97% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java rename to core-java-modules/core-java-nio/src/main/java/com/baeldung/filevisitor/FileSearchExample.java index b1b790f541..b49d6eb570 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/visitor/FileSearchExample.java +++ b/core-java-modules/core-java-nio/src/main/java/com/baeldung/filevisitor/FileSearchExample.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.visitor; +package com.baeldung.filevisitor; import java.io.IOException; import java.nio.file.*; diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java b/core-java-modules/core-java-nio/src/main/java/com/baeldung/filevisitor/FileVisitorImpl.java similarity index 94% rename from core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java rename to core-java-modules/core-java-nio/src/main/java/com/baeldung/filevisitor/FileVisitorImpl.java index aa769b5091..d86264720f 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/java/nio2/visitor/FileVisitorImpl.java +++ b/core-java-modules/core-java-nio/src/main/java/com/baeldung/filevisitor/FileVisitorImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.visitor; +package com.baeldung.filevisitor; import java.io.IOException; import java.nio.file.FileVisitResult; diff --git a/core-java-modules/core-java-nio/src/main/java/com/baeldung/file/Main.java b/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/Main.java similarity index 62% rename from core-java-modules/core-java-nio/src/main/java/com/baeldung/file/Main.java rename to core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/Main.java index d8800dd881..5aa0968ab9 100644 --- a/core-java-modules/core-java-nio/src/main/java/com/baeldung/file/Main.java +++ b/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/Main.java @@ -1,13 +1,13 @@ -package com.baeldung.file; +package com.baeldung.lines; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFilesReadAllLines; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFilesReadAllLines; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; public class Main { diff --git a/core-java-modules/core-java-nio/src/main/java/com/baeldung/file/NumberOfLineFinder.java b/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/NumberOfLineFinder.java similarity index 99% rename from core-java-modules/core-java-nio/src/main/java/com/baeldung/file/NumberOfLineFinder.java rename to core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/NumberOfLineFinder.java index 3abf82f3fa..b355295dab 100644 --- a/core-java-modules/core-java-nio/src/main/java/com/baeldung/file/NumberOfLineFinder.java +++ b/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/NumberOfLineFinder.java @@ -1,4 +1,4 @@ -package com.baeldung.file; +package com.baeldung.lines; import java.io.BufferedReader; import java.io.File; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoClient.java similarity index 98% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoClient.java index ebab715306..f42f5cdeca 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoClient.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoClient.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.async; +package com.baeldung.async; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoIntegrationTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoIntegrationTest.java similarity index 95% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoIntegrationTest.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoIntegrationTest.java index 3cfac0e90f..42053cea96 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoIntegrationTest.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.async; +package com.baeldung.async; import org.junit.After; import org.junit.Before; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoServer.java similarity index 98% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoServer.java index 01873b344a..b3f8151b7e 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoServer.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.async; +package com.baeldung.async; import java.io.File; import java.io.IOException; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoServer2.java similarity index 98% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoServer2.java index 663fc4f2ed..15b98cbf6e 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncEchoServer2.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/async/AsyncEchoServer2.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.async; +package com.baeldung.async; import java.io.File; import java.io.IOException; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/asyncfilechannel/AsyncFileChannelIntegrationTest.java similarity index 98% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/asyncfilechannel/AsyncFileChannelIntegrationTest.java index cf37b92565..68f0afec95 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/asyncfilechannel/AsyncFileChannelIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.async; +package com.baeldung.asyncfilechannel; import org.junit.Test; @@ -16,7 +16,7 @@ import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; -public class AsyncFileIntegrationTest { +public class AsyncFileChannelIntegrationTest { @Test public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException { diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/attributes/BasicAttribsIntegrationTest.java similarity index 98% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/attributes/BasicAttribsIntegrationTest.java index 4b6302e93c..a1f05d107f 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/attributes/BasicAttribsIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2.attributes; +package com.baeldung.attributes; import org.junit.BeforeClass; import org.junit.Test; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/FileIntegrationTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/file/FileIntegrationTest.java similarity index 99% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/FileIntegrationTest.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/file/FileIntegrationTest.java index d1cf81e4ce..1ae84a4dcf 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/FileIntegrationTest.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/file/FileIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.nio2; +package com.baeldung.file; import org.apache.commons.io.FileUtils; import org.junit.AfterClass; diff --git a/core-java-modules/core-java-nio/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/lines/NumberOfLineFinderUnitTest.java similarity index 71% rename from core-java-modules/core-java-nio/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/lines/NumberOfLineFinderUnitTest.java index 40ed6d6bba..661b42accd 100644 --- a/core-java-modules/core-java-nio/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/lines/NumberOfLineFinderUnitTest.java @@ -1,13 +1,13 @@ -package com.baeldung.file; +package com.baeldung.lines; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFilesReadAllLines; -import static com.baeldung.file.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFilesReadAllLines; +import static com.baeldung.lines.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; import static org.junit.Assert.assertEquals; import org.junit.Test; diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/path/PathManualTest.java similarity index 97% rename from core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java rename to core-java-modules/core-java-nio/src/test/java/com/baeldung/path/PathManualTest.java index 969dff1da2..7017fd42e7 100644 --- a/core-java-modules/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java +++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/path/PathManualTest.java @@ -1,8 +1,6 @@ -package com.baeldung.java.nio2; +package com.baeldung.path; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.Test; import java.io.IOException; import java.net.URI; @@ -10,7 +8,7 @@ import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; -import org.junit.Test; +import static org.junit.Assert.*; public class PathManualTest { diff --git a/core-java-modules/core-java-nio/src/test/resources/.gitignore b/core-java-modules/core-java-nio/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/core-java-modules/core-java-nio/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/core-java-modules/core-java-nio/src/test/resources/file.txt b/core-java-modules/core-java-nio/src/test/resources/file.txt new file mode 100644 index 0000000000..558d8bbf35 --- /dev/null +++ b/core-java-modules/core-java-nio/src/test/resources/file.txt @@ -0,0 +1 @@ +baeldung.com \ No newline at end of file diff --git a/core-java-modules/core-java-os/README.md b/core-java-modules/core-java-os/README.md index 9205628a87..f2ec3f9d48 100644 --- a/core-java-modules/core-java-os/README.md +++ b/core-java-modules/core-java-os/README.md @@ -3,9 +3,14 @@ This module contains articles about working with the operating system (OS) in Java ### Relevant Articles: + - [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) - [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) - [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api) - [Get the Current Working Directory in Java](https://www.baeldung.com/java-current-directory) +- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os) +- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) +- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java) +- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) This module uses Java 9, so make sure to have the JDK 9 installed to run it. \ No newline at end of file diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 8c5f7fe1e9..f09b62ebf2 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -42,6 +42,16 @@ ${assertj.version} test + + org.unix4j + unix4j-command + ${unix4j.version} + + + com.googlecode.grep4j + grep4j + ${grep4j.version} + @@ -77,5 +87,7 @@ 1.9 1.9 25.1-jre + 0.4 + 1.8.7 diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/printscreen/Screenshot.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java rename to core-java-modules/core-java-os/src/main/java/com/baeldung/printscreen/Screenshot.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/system/DetectOS.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/system/DetectOS.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/system/DetectOS.java rename to core-java-modules/core-java-os/src/main/java/com/baeldung/system/DetectOS.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java diff --git a/core-java-modules/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java similarity index 98% rename from core-java-modules/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java index efd7dda70f..53e9364207 100644 --- a/core-java-modules/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.shell; +package com.baeldung.java.shell; import org.junit.Assert; import org.junit.Test; diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java diff --git a/core-java-modules/core-java-security-manager/README.md b/core-java-modules/core-java-security-manager/README.md new file mode 100644 index 0000000000..a4abe7f80a --- /dev/null +++ b/core-java-modules/core-java-security-manager/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) diff --git a/core-java-modules/core-java-streams-2/README.md b/core-java-modules/core-java-streams-2/README.md new file mode 100644 index 0000000000..2ff95045c3 --- /dev/null +++ b/core-java-modules/core-java-streams-2/README.md @@ -0,0 +1,16 @@ +## Core Java streams + +This module contains articles about the Stream API in Java. + +### Relevant Articles: +- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams) +- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction) +- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany) +- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) +- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) +- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api) +- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams) +- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection) +- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend) +- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) +- More articles: [[<-- prev>]](/../core-java-streams) [[next -->]](/../core-java-streams-3) diff --git a/java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml similarity index 84% rename from java-streams-2/pom.xml rename to core-java-modules/core-java-streams-2/pom.xml index 4cebd44427..20c028edaa 100644 --- a/java-streams-2/pom.xml +++ b/core-java-modules/core-java-streams-2/pom.xml @@ -1,49 +1,53 @@ - - - 4.0.0 - com.baeldung.javastreams2 - java-streams-2 - 1.0 - java-streams-2 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator.version} - - - junit - junit - ${junit.version} - test - jar - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - UTF-8 - 1.9 - 1.9 - 3.11.1 - + + + 4.0.0 + core-java-streams-2 + 1.0 + core-java-streams-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + log4j + log4j + ${log4j.version} + + + junit + junit + ${junit.version} + test + jar + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + UTF-8 + 1.9 + 1.9 + 3.11.1 + \ No newline at end of file diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java similarity index 97% rename from java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java index 79c557524d..62d080c32c 100644 --- a/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java @@ -1,39 +1,39 @@ -package com.baeldung.reduce.application; - -import com.baeldung.reduce.entities.User; -import com.baeldung.reduce.utilities.NumberUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class Application { - - public static void main(String[] args) { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); - System.out.println(result1); - - int result2 = numbers.stream().reduce(0, Integer::sum); - System.out.println(result2); - - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); - System.out.println(result3); - - String result4 = letters.stream().reduce("", String::concat); - System.out.println(result4); - - String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); - System.out.println(result5); - - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result6); - - String result7 = letters.parallelStream().reduce("", String::concat); - System.out.println(result7); - - int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result8); - } -} +package com.baeldung.reduce.application; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Application { + + public static void main(String[] args) { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + System.out.println(result1); + + int result2 = numbers.stream().reduce(0, Integer::sum); + System.out.println(result2); + + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); + System.out.println(result3); + + String result4 = letters.stream().reduce("", String::concat); + System.out.println(result4); + + String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + System.out.println(result5); + + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result6); + + String result7 = letters.parallelStream().reduce("", String::concat); + System.out.println(result7); + + int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result8); + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java similarity index 97% rename from java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java index af4a9276a9..ecb0347e96 100644 --- a/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java @@ -1,52 +1,52 @@ -package com.baeldung.reduce.benchmarks; - -import com.baeldung.reduce.entities.User; -import java.util.ArrayList; -import java.util.List; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.RunnerException; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; - -@State(Scope.Thread) -@BenchmarkMode(Mode.AverageTime) -public class JMHStreamReduceBenchMark { - - private final List userList = createUsers(); - - public static void main(String[] args) throws RunnerException { - - Options options = new OptionsBuilder() - .include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1) - .forks(1).shouldFailOnError(true).shouldDoGC(true) - .jvmArgs("-server").build(); - new Runner(options).run(); - } - - private List createUsers() { - List users = new ArrayList<>(); - for (int i = 0; i <= 1000000; i++) { - users.add(new User("John" + i, i)); - } - return users; - } - - @Benchmark - public Integer executeReduceOnParallelizedStream() { - return this.userList - .parallelStream() - .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } - - @Benchmark - public Integer executeReduceOnSequentialStream() { - return this.userList - .stream() - .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } -} +package com.baeldung.reduce.benchmarks; + +import com.baeldung.reduce.entities.User; +import java.util.ArrayList; +import java.util.List; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +public class JMHStreamReduceBenchMark { + + private final List userList = createUsers(); + + public static void main(String[] args) throws RunnerException { + + Options options = new OptionsBuilder() + .include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } + + private List createUsers() { + List users = new ArrayList<>(); + for (int i = 0; i <= 1000000; i++) { + users.add(new User("John" + i, i)); + } + return users; + } + + @Benchmark + public Integer executeReduceOnParallelizedStream() { + return this.userList + .parallelStream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } + + @Benchmark + public Integer executeReduceOnSequentialStream() { + return this.userList + .stream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } +} diff --git a/java-streams/src/main/java/com/baeldung/reduce/entities/User.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java similarity index 94% rename from java-streams/src/main/java/com/baeldung/reduce/entities/User.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java index a17c6a02b6..6e0a529de6 100644 --- a/java-streams/src/main/java/com/baeldung/reduce/entities/User.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java @@ -1,25 +1,25 @@ -package com.baeldung.reduce.entities; - -public class User { - - private final String name; - private final int age; - - public User(String name, int age) { - this.name = name; - this.age = age; - } - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - @Override - public String toString() { - return "User{" + "name=" + name + ", age=" + age + '}'; - } -} +package com.baeldung.reduce.entities; + +public class User { + + private final String name; + private final int age; + + public User(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "User{" + "name=" + name + ", age=" + age + '}'; + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java similarity index 97% rename from java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java index a7a4b8df29..38d5b50120 100644 --- a/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java @@ -1,52 +1,52 @@ -package com.baeldung.reduce.utilities; - -import java.util.List; -import java.util.function.BiFunction; -import java.util.logging.Level; -import java.util.logging.Logger; - -public abstract class NumberUtils { - - private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); - - public static int divideListElements(List values, Integer divider) { - return values.stream() - .reduce(0, (a, b) -> { - try { - return a / divider + b / divider; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return 0; - }); - } - - public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { - return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); - } - - public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { - BiFunction division = (a, b) -> a / b; - return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); - } - - private static int divide(int value, int factor) { - int result = 0; - try { - result = value / factor; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return result; - } - - private static int applyFunction(BiFunction function, int a, int b) { - try { - return function.apply(a, b); - } - catch(Exception e) { - LOGGER.log(Level.INFO, "Exception thrown!"); - } - return 0; - } -} +package com.baeldung.reduce.utilities; + +import java.util.List; +import java.util.function.BiFunction; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class NumberUtils { + + private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); + + public static int divideListElements(List values, Integer divider) { + return values.stream() + .reduce(0, (a, b) -> { + try { + return a / divider + b / divider; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return 0; + }); + } + + public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { + return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); + } + + public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { + BiFunction division = (a, b) -> a / b; + return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); + } + + private static int divide(int value, int factor) { + int result = 0; + try { + result = value / factor; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return result; + } + + private static int applyFunction(BiFunction function, int a, int b) { + try { + return function.apply(a, b); + } + catch(Exception e) { + LOGGER.log(Level.INFO, "Exception thrown!"); + } + return 0; + } +} diff --git a/java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/streams/MyImmutableListCollector.java similarity index 93% rename from java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/streams/MyImmutableListCollector.java index cf6b3601c3..6d515bfb46 100644 --- a/java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/streams/MyImmutableListCollector.java @@ -1,4 +1,4 @@ -package com.baeldung.stream.mycollectors; +package com.baeldung.streams; import java.util.ArrayList; import java.util.Collections; diff --git a/core-java-modules/core-java-datetime/src/main/resources/logback.xml b/core-java-modules/core-java-streams-2/src/main/resources/logback.xml similarity index 100% rename from core-java-modules/core-java-datetime/src/main/resources/logback.xml rename to core-java-modules/core-java-streams-2/src/main/resources/logback.xml diff --git a/java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java similarity index 100% rename from java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java diff --git a/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/reduce/StreamReduceUnitTest.java similarity index 95% rename from java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/reduce/StreamReduceUnitTest.java index 564d614017..21eedf953e 100644 --- a/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/reduce/StreamReduceUnitTest.java @@ -1,79 +1,80 @@ -package com.baeldung.reduce.tests; - -import com.baeldung.reduce.entities.User; -import com.baeldung.reduce.utilities.NumberUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class StreamReduceUnitTest { - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, Integer::sum); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (partialString, element) -> partialString + element); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); - assertThat(result).isEqualTo("ABCDE"); - } - - @Test - public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - assertThat(result).isEqualTo(65); - } - - @Test - public void givenStringList_whenReduceWithParallelStream_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.parallelStream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); - } -} +package com.baeldung.reduce; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StreamReduceUnitTest { + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, Integer::sum); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString + element); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + assertThat(result).isEqualTo("ABCDE"); + } + + @Test + public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + assertThat(result).isEqualTo(65); + } + + @Test + public void givenStringList_whenReduceWithParallelStream_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.parallelStream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); + } +} diff --git a/java-streams/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Detail.java similarity index 85% rename from java-streams/src/main/java/com/baeldung/java_8_features/Detail.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Detail.java index 811937dba7..d2f5774b24 100644 --- a/java-streams/src/main/java/com/baeldung/java_8_features/Detail.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Detail.java @@ -1,4 +1,4 @@ -package com.baeldung.java_8_features; +package com.baeldung.streams; import java.util.Arrays; import java.util.List; diff --git a/java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8FindAnyFindFirstUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8FindAnyFindFirstUnitTest.java index 5f52fe375e..934d7b3542 100644 --- a/java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8FindAnyFindFirstUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8.streams; +package com.baeldung.streams; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java similarity index 99% rename from java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java index 75cfbc049f..c4e1f2b3cb 100644 --- a/java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.java8.streams; +package com.baeldung.streams; -import com.baeldung.stream.Product; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; diff --git a/java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamsUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamsUnitTest.java index e40f9f9506..f46fa79b08 100644 --- a/java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamsUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.java8; +package com.baeldung.streams; -import com.baeldung.java_8_features.Detail; import org.junit.Before; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/PeekUnitTest.java similarity index 98% rename from java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/PeekUnitTest.java index a3a2816e9c..97af4149d3 100644 --- a/java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/PeekUnitTest.java @@ -1,13 +1,13 @@ -package com.baeldung.stream; +package com.baeldung.streams; -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.StringWriter; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; public class PeekUnitTest { diff --git a/java-streams/src/main/java/com/baeldung/stream/Product.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Product.java similarity index 96% rename from java-streams/src/main/java/com/baeldung/stream/Product.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Product.java index e99a969b81..7883f055a1 100644 --- a/java-streams/src/main/java/com/baeldung/stream/Product.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Product.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.streams; import java.util.List; import java.util.stream.Stream; diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamAddUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamAddUnitTest.java index d0745b8bc9..1fada26de5 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamAddUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.streams; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamMapUnitTest.java similarity index 96% rename from java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamMapUnitTest.java index 5cb2a274d1..509a3a3569 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamMapUnitTest.java @@ -1,16 +1,13 @@ -package com.baeldung.stream; +package com.baeldung.streams; import org.junit.Before; import org.junit.Test; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java similarity index 81% rename from java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java index bd540201d2..e5339d8327 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java @@ -1,20 +1,12 @@ -package com.baeldung.stream; - -import static java.util.stream.Collectors.collectingAndThen; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toSet; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.IntStream; +package com.baeldung.streams; +import com.google.common.collect.ImmutableList; import org.junit.Test; -import com.baeldung.stream.mycollectors.MyImmutableListCollector; -import com.google.common.collect.ImmutableList; +import java.util.*; +import java.util.stream.IntStream; + +import static java.util.stream.Collectors.*; public class StreamToImmutableUnitTest { diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/removeitem/StreamOperateAndRemoveUnitTest.java similarity index 98% rename from java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/removeitem/StreamOperateAndRemoveUnitTest.java index c5aa9a1651..194d0bd4d6 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/removeitem/StreamOperateAndRemoveUnitTest.java @@ -1,9 +1,4 @@ -package com.baeldung.stream; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Predicate; -import java.util.stream.Collectors; +package com.baeldung.streams.removeitem; import org.junit.Assert; import org.junit.Before; @@ -11,6 +6,11 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + public class StreamOperateAndRemoveUnitTest { private List itemList; diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md new file mode 100644 index 0000000000..4b2c9ed94c --- /dev/null +++ b/core-java-modules/core-java-streams-3/README.md @@ -0,0 +1,11 @@ +## Core Java streams + +This module contains articles about the Stream API in Java. + +### Relevant Articles: +- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap) +- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) +- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) +- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) +- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) +- More articles: [[<-- prev>]](/../core-java-streams-2) \ No newline at end of file diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml new file mode 100644 index 0000000000..b5b21a4368 --- /dev/null +++ b/core-java-modules/core-java-streams-3/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + core-java-streams-3 + 0.1.0-SNAPSHOT + core-java-streams-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-streams-3 + + + src/main/resources + true + + + + + + + 3.6.1 + + 2.22.1 + + diff --git a/core-java-modules/core-java-streams/src/main/java/com/baeldung/forEach/ReverseList.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/forEach/ReverseList.java similarity index 98% rename from core-java-modules/core-java-streams/src/main/java/com/baeldung/forEach/ReverseList.java rename to core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/forEach/ReverseList.java index b2ce77a9f6..c4128d9b72 100644 --- a/core-java-modules/core-java-streams/src/main/java/com/baeldung/forEach/ReverseList.java +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/forEach/ReverseList.java @@ -1,4 +1,4 @@ -package com.baeldung.forEach; +package com.baeldung.streams.forEach; import java.util.ArrayList; import java.util.Arrays; diff --git a/java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/primitivestreams/PrimitiveStreams.java similarity index 90% rename from java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java rename to core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/primitivestreams/PrimitiveStreams.java index b0afb65a35..fb2001f10f 100644 --- a/java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/primitivestreams/PrimitiveStreams.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.streams.primitivestreams; import java.util.Arrays; import java.util.stream.IntStream; diff --git a/java-dates/src/main/resources/logback.xml b/core-java-modules/core-java-streams-3/src/main/resources/logback.xml similarity index 100% rename from java-dates/src/main/resources/logback.xml rename to core-java-modules/core-java-streams-3/src/main/resources/logback.xml diff --git a/core-java-modules/core-java-streams/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java similarity index 99% rename from core-java-modules/core-java-streams/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java index e742635758..6afc9f4182 100644 --- a/core-java-modules/core-java-streams/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.collectors; +package com.baeldung.streams.collectors; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; diff --git a/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/conditional/StreamForEachIfElseUnitTest.java similarity index 96% rename from core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/conditional/StreamForEachIfElseUnitTest.java index b5d26eb6a8..a49a092864 100644 --- a/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/conditional/StreamForEachIfElseUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.stream.conditional; +package com.baeldung.streams.conditional; import java.util.Arrays; import java.util.List; diff --git a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/primitivestreams/PrimitiveStreamsUnitTest.java similarity index 98% rename from java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/primitivestreams/PrimitiveStreamsUnitTest.java index 67954f0bba..18966425e4 100644 --- a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/primitivestreams/PrimitiveStreamsUnitTest.java @@ -1,14 +1,14 @@ -package com.baeldung.stream; +package com.baeldung.streams.primitivestreams; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class PrimitiveStreamsUnitTest { diff --git a/java-dates/.gitignore b/core-java-modules/core-java-streams/.gitignore similarity index 100% rename from java-dates/.gitignore rename to core-java-modules/core-java-streams/.gitignore diff --git a/core-java-modules/core-java-streams/README.md b/core-java-modules/core-java-streams/README.md index e97641c221..e556c231fe 100644 --- a/core-java-modules/core-java-streams/README.md +++ b/core-java-modules/core-java-streams/README.md @@ -1,9 +1,16 @@ -========= +## Core Java streams -## Core Java 8 Cookbooks and Examples +This module contains articles about the Stream API in Java. ### Relevant Articles: -- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap) -- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) -- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) -- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) \ No newline at end of file +- [Java 8 and Infinite Streams](https://www.baeldung.com/java-inifinite-streams) +- [How to Get the Last Element of a Stream in Java?](https://www.baeldung.com/java-stream-last-element) +- [“Stream has already been operated upon or closed” Exception in Java](https://www.baeldung.com/java-stream-operated-upon-or-closed-exception) +- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream) +- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices) +- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) +- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) +- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) +- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) +- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum) +- More articles: [[next -->]](/../core-java-streams-2) \ No newline at end of file diff --git a/core-java-modules/core-java-streams/pom.xml b/core-java-modules/core-java-streams/pom.xml index 96d97f3759..9b68c8dded 100644 --- a/core-java-modules/core-java-streams/pom.xml +++ b/core-java-modules/core-java-streams/pom.xml @@ -14,6 +14,34 @@ + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + provided + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + org.assertj @@ -21,6 +49,36 @@ ${assertj.version} test + + com.codepoetics + protonpack + ${protonpack.version} + + + io.vavr + vavr + ${vavr.version} + + + one.util + streamex + ${streamex.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.aspectj + aspectjweaver + ${asspectj.version} + + + pl.touk + throwing-function + ${throwing-function.version} + @@ -31,10 +89,33 @@ true + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + -parameters + + + + + 0.9.0 + 1.15 + 0.6.5 + 2.10 + 1.3 - 3.6.1 + 3.11.1 + 1.8.9 + 3.1 + 1.8 + 1.8 diff --git a/java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java diff --git a/java-streams/src/main/java/com/baeldung/stream/StreamApi.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamApi.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/StreamApi.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamApi.java diff --git a/java-streams/src/main/java/com/baeldung/stream/StreamIndices.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamIndices.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/StreamIndices.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamIndices.java diff --git a/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/filter/Customer.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/filter/Customer.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/filter/Customer.java diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java similarity index 94% rename from java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java index 3170b1fb31..c44aaf8005 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java @@ -1,8 +1,8 @@ -package com.baeldung.stream.sum; - -public class ArithmeticUtils { - - public static int add(int a, int b) { - return a + b; - } -} +package com.baeldung.stream.sum; + +public class ArithmeticUtils { + + public static int add(int a, int b) { + return a + b; + } +} diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/Item.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/Item.java similarity index 94% rename from java-streams/src/main/java/com/baeldung/stream/sum/Item.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/Item.java index 2f162d6eda..28a1737db8 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/Item.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/Item.java @@ -1,31 +1,31 @@ -package com.baeldung.stream.sum; - -public class Item { - - private int id; - private Integer price; - - public Item(int id, Integer price) { - super(); - this.id = id; - this.price = price; - } - - // Standard getters and setters - public long getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public Integer getPrice() { - return price; - } - - public void setPrice(Integer price) { - this.price = price; - } - -} +package com.baeldung.stream.sum; + +public class Item { + + private int id; + private Integer price; + + public Item(int id, Integer price) { + super(); + this.id = id; + this.price = price; + } + + // Standard getters and setters + public long getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Integer getPrice() { + return price; + } + + public void setPrice(Integer price) { + this.price = price; + } + +} diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java similarity index 96% rename from java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java index 2f63cf8629..ea6459d360 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java @@ -1,59 +1,59 @@ -package com.baeldung.stream.sum; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -public class StreamSumCalculator { - - public static Integer getSumUsingCustomizedAccumulator(List integers) { - return integers.stream() - .reduce(0, ArithmeticUtils::add); - - } - - public static Integer getSumUsingJavaAccumulator(List integers) { - return integers.stream() - .reduce(0, Integer::sum); - - } - - public static Integer getSumUsingReduce(List integers) { - return integers.stream() - .reduce(0, (a, b) -> a + b); - - } - - public static Integer getSumUsingCollect(List integers) { - - return integers.stream() - .collect(Collectors.summingInt(Integer::intValue)); - - } - - public static Integer getSumUsingSum(List integers) { - - return integers.stream() - .mapToInt(Integer::intValue) - .sum(); - } - - public static Integer getSumOfMapValues(Map map) { - - return map.values() - .stream() - .mapToInt(Integer::valueOf) - .sum(); - } - - public static Integer getSumIntegersFromString(String str) { - - Integer sum = Arrays.stream(str.split(" ")) - .filter((s) -> s.matches("\\d+")) - .mapToInt(Integer::valueOf) - .sum(); - - return sum; - } -} +package com.baeldung.stream.sum; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class StreamSumCalculator { + + public static Integer getSumUsingCustomizedAccumulator(List integers) { + return integers.stream() + .reduce(0, ArithmeticUtils::add); + + } + + public static Integer getSumUsingJavaAccumulator(List integers) { + return integers.stream() + .reduce(0, Integer::sum); + + } + + public static Integer getSumUsingReduce(List integers) { + return integers.stream() + .reduce(0, (a, b) -> a + b); + + } + + public static Integer getSumUsingCollect(List integers) { + + return integers.stream() + .collect(Collectors.summingInt(Integer::intValue)); + + } + + public static Integer getSumUsingSum(List integers) { + + return integers.stream() + .mapToInt(Integer::intValue) + .sum(); + } + + public static Integer getSumOfMapValues(Map map) { + + return map.values() + .stream() + .mapToInt(Integer::valueOf) + .sum(); + } + + public static Integer getSumIntegersFromString(String str) { + + Integer sum = Arrays.stream(str.split(" ")) + .filter((s) -> s.matches("\\d+")) + .mapToInt(Integer::valueOf) + .sum(); + + return sum; + } +} diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java similarity index 96% rename from java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java index b83616928e..8a162429d2 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java @@ -1,38 +1,38 @@ -package com.baeldung.stream.sum; - -import java.util.List; -import java.util.stream.Collectors; - -public class StreamSumCalculatorWithObject { - - public static Integer getSumUsingCustomizedAccumulator(List items) { - return items.stream() - .map(x -> x.getPrice()) - .reduce(0, ArithmeticUtils::add); - } - - public static Integer getSumUsingJavaAccumulator(List items) { - return items.stream() - .map(x -> x.getPrice()) - .reduce(0, Integer::sum); - } - - public static Integer getSumUsingReduce(List items) { - return items.stream() - .map(item -> item.getPrice()) - .reduce(0, (a, b) -> a + b); - } - - public static Integer getSumUsingCollect(List items) { - return items.stream() - .map(x -> x.getPrice()) - .collect(Collectors.summingInt(Integer::intValue)); - } - - public static Integer getSumUsingSum(List items) { - return items.stream() - .mapToInt(x -> x.getPrice()) - .sum(); - } - -} +package com.baeldung.stream.sum; + +import java.util.List; +import java.util.stream.Collectors; + +public class StreamSumCalculatorWithObject { + + public static Integer getSumUsingCustomizedAccumulator(List items) { + return items.stream() + .map(x -> x.getPrice()) + .reduce(0, ArithmeticUtils::add); + } + + public static Integer getSumUsingJavaAccumulator(List items) { + return items.stream() + .map(x -> x.getPrice()) + .reduce(0, Integer::sum); + } + + public static Integer getSumUsingReduce(List items) { + return items.stream() + .map(item -> item.getPrice()) + .reduce(0, (a, b) -> a + b); + } + + public static Integer getSumUsingCollect(List items) { + return items.stream() + .map(x -> x.getPrice()) + .collect(Collectors.summingInt(Integer::intValue)); + } + + public static Integer getSumUsingSum(List items) { + return items.stream() + .mapToInt(x -> x.getPrice()) + .sum(); + } + +} diff --git a/java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/conversion/IterableStreamConversionUnitTest.java similarity index 96% rename from java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/conversion/IterableStreamConversionUnitTest.java index 99e8088054..f65f91a768 100644 --- a/java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/conversion/IterableStreamConversionUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.conversion; +package com.baeldung.conversion; import org.junit.Assert; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java index a496e18b2d..69edc4f535 100644 --- a/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java @@ -1,35 +1,35 @@ -package com.baeldung.stream; - -import static org.junit.Assert.fail; - -import java.util.Optional; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import org.junit.Test; - -public class SupplierStreamUnitTest { - - @Test(expected = IllegalStateException.class) - public void givenStream_whenStreamUsedTwice_thenThrowException() { - Stream stringStream = Stream.of("A", "B", "C", "D"); - Optional result1 = stringStream.findAny(); - System.out.println(result1.get()); - Optional result2 = stringStream.findFirst(); - System.out.println(result2.get()); - } - - @Test - public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() { - try { - Supplier> streamSupplier = () -> Stream.of("A", "B", "C", "D"); - Optional result1 = streamSupplier.get().findAny(); - System.out.println(result1.get()); - Optional result2 = streamSupplier.get().findFirst(); - System.out.println(result2.get()); - } catch (IllegalStateException e) { - fail(); - } - } - +package com.baeldung.stream; + +import static org.junit.Assert.fail; + +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import org.junit.Test; + +public class SupplierStreamUnitTest { + + @Test(expected = IllegalStateException.class) + public void givenStream_whenStreamUsedTwice_thenThrowException() { + Stream stringStream = Stream.of("A", "B", "C", "D"); + Optional result1 = stringStream.findAny(); + System.out.println(result1.get()); + Optional result2 = stringStream.findFirst(); + System.out.println(result2.get()); + } + + @Test + public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() { + try { + Supplier> streamSupplier = () -> Stream.of("A", "B", "C", "D"); + Optional result1 = streamSupplier.get().findAny(); + System.out.println(result1.get()); + Optional result2 = streamSupplier.get().findFirst(); + System.out.println(result2.get()); + } catch (IllegalStateException e) { + fail(); + } + } + } \ No newline at end of file diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java index 46e1af9a4a..f03703154a 100644 --- a/java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java @@ -1,136 +1,136 @@ -package com.baeldung.stream.sum; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.Test; - -public class StreamSumUnitTest { - - @Test - public void givenListOfIntegersWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingCustomizedAccumulator(integers); - assertEquals(15, sum.intValue()); - - } - - @Test - public void givenListOfIntegersWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingJavaAccumulator(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfIntegersWhenSummingUsingReduceThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingReduce(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfIntegersWhenSummingUsingCollectThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingCollect(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfIntegersWhenSummingUsingSumThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingSum(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingCustomizedAccumulator(items); - assertEquals(90, sum.intValue()); - - } - - @Test - public void givenListOfItemsWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingJavaAccumulator(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingReduceThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingReduce(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingCollectThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingCollect(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingSumThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingSum(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenMapWhenSummingThenCorrectValueReturned() { - Map map = new HashMap(); - map.put(1, 10); - map.put(2, 15); - map.put(3, 25); - map.put(4, 40); - - Integer sum = StreamSumCalculator.getSumOfMapValues(map); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenStringWhenSummingThenCorrectValueReturned() { - String string = "Item1 10 Item2 25 Item3 30 Item4 45"; - - Integer sum = StreamSumCalculator.getSumIntegersFromString(string); - assertEquals(110, sum.intValue()); - } - -} +package com.baeldung.stream.sum; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +public class StreamSumUnitTest { + + @Test + public void givenListOfIntegersWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingCustomizedAccumulator(integers); + assertEquals(15, sum.intValue()); + + } + + @Test + public void givenListOfIntegersWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingJavaAccumulator(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfIntegersWhenSummingUsingReduceThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingReduce(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfIntegersWhenSummingUsingCollectThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingCollect(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfIntegersWhenSummingUsingSumThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingSum(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingCustomizedAccumulator(items); + assertEquals(90, sum.intValue()); + + } + + @Test + public void givenListOfItemsWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingJavaAccumulator(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingReduceThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingReduce(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingCollectThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingCollect(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingSumThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingSum(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenMapWhenSummingThenCorrectValueReturned() { + Map map = new HashMap(); + map.put(1, 10); + map.put(2, 15); + map.put(3, 25); + map.put(4, 40); + + Integer sum = StreamSumCalculator.getSumOfMapValues(map); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenStringWhenSummingThenCorrectValueReturned() { + String string = "Item1 10 Item2 25 Item3 30 Item4 45"; + + Integer sum = StreamSumCalculator.getSumIntegersFromString(string); + assertEquals(110, sum.intValue()); + } + +} diff --git a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java diff --git a/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java diff --git a/core-java-modules/core-java-9/.gitignore b/core-java-modules/core-java-streams/src/test/resources/.gitignore similarity index 100% rename from core-java-modules/core-java-9/.gitignore rename to core-java-modules/core-java-streams/src/test/resources/.gitignore diff --git a/core-java-modules/core-java-string-algorithms-2/README.md b/core-java-modules/core-java-string-algorithms-2/README.md new file mode 100644 index 0000000000..2cd64e1920 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-2/README.md @@ -0,0 +1,16 @@ +## Java String Algorithms + +This module contains articles about string-related algorithms. + +### Relevant Articles: +- [How to Remove the Last Character of a String?](https://www.baeldung.com/java-remove-last-character-of-string) +- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) +- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) +- [Remove or Replace Part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) +- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) +- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) +- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) +- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) +- [Counting Words in a String](https://www.baeldung.com/java-word-counting) +- [Finding the Difference Between Two Strings](https://www.baeldung.com/java-difference-between-two-strings) +- More articles: [[<-- prev]](../core-java-string-algorithms) diff --git a/core-java-modules/core-java-string-algorithms-2/pom.xml b/core-java-modules/core-java-string-algorithms-2/pom.xml new file mode 100644 index 0000000000..5b0e710bb8 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-2/pom.xml @@ -0,0 +1,67 @@ + + 4.0.0 + core-java-string-algorithms-2 + 0.1.0-SNAPSHOT + jar + core-java-string-algorithms-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + com.google.guava + guava + ${guava.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-core.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.bitbucket.cowwoc + diff-match-patch + ${diff-match-path.version} + test + + + + + core-java-string-algorithms-2 + + + src/main/resources + true + + + + + + 3.8.1 + 3.6.1 + 1.2 + + + diff --git a/java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/addchar/AppendCharAtPositionX.java similarity index 97% rename from java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java rename to core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/addchar/AppendCharAtPositionX.java index ad203ab348..92bb9a9832 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java +++ b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/addchar/AppendCharAtPositionX.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.string; +package com.baeldung.addchar; /** * @author swpraman diff --git a/java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/padding/StringPaddingUtil.java similarity index 96% rename from java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java rename to core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/padding/StringPaddingUtil.java index 80d05bb42a..1de82620c0 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java +++ b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/padding/StringPaddingUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.string.padding; +package com.baeldung.padding; public class StringPaddingUtil { diff --git a/java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/removelastchar/StringHelper.java similarity index 95% rename from java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java rename to core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/removelastchar/StringHelper.java index dac0d1272e..ebcc283851 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java +++ b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/removelastchar/StringHelper.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.removelastchar; import java.util.Optional; diff --git a/java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java similarity index 97% rename from java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java rename to core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java index c9d748e897..386d34e0ac 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java +++ b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java @@ -1,9 +1,8 @@ -package com.baeldung.string.removeleadingtrailingchar; +package com.baeldung.removeleadingtrailingchar; -import org.apache.commons.lang3.StringUtils; - import com.google.common.base.CharMatcher; +import org.apache.commons.lang3.StringUtils; public class RemoveLeadingAndTrailingZeroes { diff --git a/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/replacechar/ReplaceCharacterInString.java similarity index 96% rename from java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java rename to core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/replacechar/ReplaceCharacterInString.java index 2cc67f0b51..29fb28a85b 100644 --- a/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java +++ b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/replacechar/ReplaceCharacterInString.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.replacechar; public class ReplaceCharacterInString { diff --git a/java-strings-3/src/main/java/com/baeldung/string/wordcount/WordCounter.java b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/wordcount/WordCounter.java similarity index 97% rename from java-strings-3/src/main/java/com/baeldung/string/wordcount/WordCounter.java rename to core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/wordcount/WordCounter.java index 30275773a6..9963c3486b 100644 --- a/java-strings-3/src/main/java/com/baeldung/string/wordcount/WordCounter.java +++ b/core-java-modules/core-java-string-algorithms-2/src/main/java/com/baeldung/wordcount/WordCounter.java @@ -1,4 +1,4 @@ -package com.baeldung.string.wordcount; +package com.baeldung.wordcount; import java.util.StringTokenizer; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/addchar/AppendCharAtPositionXUnitTest.java similarity index 99% rename from java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/addchar/AppendCharAtPositionXUnitTest.java index 7c5409fe29..e850cf1954 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/addchar/AppendCharAtPositionXUnitTest.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.string; +package com.baeldung.addchar; import static org.junit.Assert.assertEquals; diff --git a/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/containchar/StringContainingCharactersUnitTest.java similarity index 99% rename from java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/containchar/StringContainingCharactersUnitTest.java index be79103e6b..3b0e545584 100644 --- a/java-strings/src/test/java/com/baeldung/string/StringContainingCharactersUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/containchar/StringContainingCharactersUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.containchar; import org.junit.Test; diff --git a/java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/join/StringFromPrimitiveArrayUnitTest.java similarity index 99% rename from java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/join/StringFromPrimitiveArrayUnitTest.java index c93089e543..f6c9141c3f 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/join/StringFromPrimitiveArrayUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.join; import com.google.common.base.Joiner; import com.google.common.primitives.Chars; diff --git a/java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/padding/StringPaddingUtilUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/padding/StringPaddingUtilUnitTest.java index f6a077a88e..d8ef500b30 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/padding/StringPaddingUtilUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.padding; +package com.baeldung.padding; import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/removelastchar/RemoveLastCharUnitTest.java similarity index 98% rename from java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/removelastchar/RemoveLastCharUnitTest.java index eb86e84905..e88158deb9 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/removelastchar/RemoveLastCharUnitTest.java @@ -1,12 +1,12 @@ -package com.baeldung.string; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +package com.baeldung.removelastchar; import org.apache.commons.lang3.StringUtils; import org.junit.Test; -public class StringHelperUnitTest { +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class RemoveLastCharUnitTest { public static final String TEST_STRING = "abcdef"; public static final String NULL_STRING = null; diff --git a/java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java similarity index 99% rename from java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java index 55f932fea1..5dec58eea9 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java @@ -1,13 +1,13 @@ -package com.baeldung.string.removeleadingtrailingchar; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.stream.Stream; +package com.baeldung.removeleadingtrailingchar; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + public class RemoveLeadingAndTrailingZeroesUnitTest { public static Stream leadingZeroTestProvider() { diff --git a/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/replacechar/ReplaceCharInStringUnitTest.java similarity index 92% rename from java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/replacechar/ReplaceCharInStringUnitTest.java index c234c6953c..1e33a7f09d 100644 --- a/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/replacechar/ReplaceCharInStringUnitTest.java @@ -1,8 +1,9 @@ -package com.baeldung.string; +package com.baeldung.replacechar; import org.junit.Test; import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; public class ReplaceCharInStringUnitTest { private ReplaceCharacterInString characterInString = new ReplaceCharacterInString(); diff --git a/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/replaceremove/StringReplaceAndRemoveUnitTest.java similarity index 98% rename from java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/replaceremove/StringReplaceAndRemoveUnitTest.java index 4d2b54241b..fe71aa6974 100644 --- a/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/replaceremove/StringReplaceAndRemoveUnitTest.java @@ -1,7 +1,7 @@ -package com.baeldung.string; +package com.baeldung.replaceremove; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.RegExUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.Test; import static org.junit.Assert.assertFalse; diff --git a/java-strings-3/src/test/java/com/baeldung/stringdiff/StringDiffBenchmarkUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/stringdiff/StringDiffBenchmarkUnitTest.java similarity index 100% rename from java-strings-3/src/test/java/com/baeldung/stringdiff/StringDiffBenchmarkUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/stringdiff/StringDiffBenchmarkUnitTest.java diff --git a/java-strings-3/src/test/java/com/baeldung/stringdiff/StringDiffUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/stringdiff/StringDiffUnitTest.java similarity index 100% rename from java-strings-3/src/test/java/com/baeldung/stringdiff/StringDiffUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/stringdiff/StringDiffUnitTest.java diff --git a/java-strings-3/src/test/java/com/baeldung/string/wordcount/WordCountUnitTest.java b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/wordcount/WordCountUnitTest.java similarity index 97% rename from java-strings-3/src/test/java/com/baeldung/string/wordcount/WordCountUnitTest.java rename to core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/wordcount/WordCountUnitTest.java index fdd045978f..bdfee61d5a 100644 --- a/java-strings-3/src/test/java/com/baeldung/string/wordcount/WordCountUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/wordcount/WordCountUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.wordcount; +package com.baeldung.wordcount; import static org.junit.Assert.assertEquals; diff --git a/core-java-modules/core-java-string-algorithms/README.md b/core-java-modules/core-java-string-algorithms/README.md new file mode 100644 index 0000000000..70a4b5ffaf --- /dev/null +++ b/core-java-modules/core-java-string-algorithms/README.md @@ -0,0 +1,16 @@ +## Java String Algorithms + +This module contains articles about string-related algorithms. + +### Relevant Articles: +- [Check If a String Is a Palindrome](https://www.baeldung.com/java-palindrome) +- [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars) +- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) +- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) +- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string) +- [Check If a String Is a Pangram in Java](https://www.baeldung.com/java-string-pangram) +- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) +- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) +- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) +- More articles: [[next -->]](../core-java-string-algorithms-2) diff --git a/java-strings-ops/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml similarity index 57% rename from java-strings-ops/pom.xml rename to core-java-modules/core-java-string-algorithms/pom.xml index b6a7ea2728..f1b7499b6d 100644 --- a/java-strings-ops/pom.xml +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -1,36 +1,33 @@ 4.0.0 - com.baeldung - java-strings-ops + core-java-string-algorithms 0.1.0-SNAPSHOT jar - java-strings-ops + core-java-string-algorithms com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java + + com.google.guava + guava + ${guava.version} + org.apache.commons commons-lang3 ${commons-lang3.version} - log4j - log4j - ${log4j.version} - - - - org.assertj - assertj-core - ${assertj.version} - test + org.ahocorasick + ahocorasick + ${ahocorasick.version} org.openjdk.jmh @@ -40,60 +37,37 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh-generator.version} + ${jmh-core.version} - com.google.guava - guava - ${guava.version} + com.vdurmont + emoji-java + ${emoji-java.version} - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter-api.version} + org.assertj + assertj-core + ${assertj.version} test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - java-strings-ops + core-java-string-algorithms src/main/resources true - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - 3.8.1 - - 3.6.1 27.0.1-jre - 5.3.1 + 0.4.0 + 3.6.1 + 4.0.0 diff --git a/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/matchwords/MatchWords.java similarity index 92% rename from java-strings-2/src/main/java/com/baeldung/string/MatchWords.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/matchwords/MatchWords.java index 0cad52c320..b5b7e92d8e 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/matchwords/MatchWords.java @@ -1,14 +1,12 @@ -package com.baeldung.string; +package com.baeldung.matchwords; import org.ahocorasick.trie.Emit; -import org.ahocorasick.trie.Token; import org.ahocorasick.trie.Trie; -import java.util.*; -import java.util.function.Function; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; public class MatchWords { diff --git a/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/palindrom/Palindrome.java similarity index 98% rename from java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/palindrom/Palindrome.java index 97d4d36d07..4a98e6583a 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/palindrom/Palindrome.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.palindrom; import java.util.stream.IntStream; diff --git a/java-strings-2/src/main/java/com/baeldung/string/Pangram.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/pangram/Pangram.java similarity index 98% rename from java-strings-2/src/main/java/com/baeldung/string/Pangram.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/pangram/Pangram.java index c09b0c1d29..ca2a44280c 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/Pangram.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/pangram/Pangram.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.pangram; import java.util.Arrays; import java.util.Map; diff --git a/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/removeduplicates/RemoveDuplicateFromString.java similarity index 98% rename from java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/removeduplicates/RemoveDuplicateFromString.java index d8fd9c4b14..a000f4dbd6 100644 --- a/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/removeduplicates/RemoveDuplicateFromString.java @@ -1,4 +1,4 @@ -package com.baeldung.stringduplicates; +package com.baeldung.removeduplicates; import java.util.Arrays; import java.util.HashSet; diff --git a/java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/repetition/SubstringRepetition.java similarity index 94% rename from java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/repetition/SubstringRepetition.java index 466ce9146b..6715367a19 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/repetition/SubstringRepetition.java @@ -1,4 +1,4 @@ -package com.baeldung.string.repetition; +package com.baeldung.repetition; public class SubstringRepetition { diff --git a/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java similarity index 97% rename from java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java index 1a58d09598..5236f14ccd 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java @@ -1,4 +1,4 @@ -package com.baeldung.string.reverse; +package com.baeldung.reverse; import org.apache.commons.lang3.StringUtils; diff --git a/java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/searching/WordIndexer.java similarity index 96% rename from java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/searching/WordIndexer.java index 1bcad6dd32..c7550f8e16 100644 --- a/java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/searching/WordIndexer.java @@ -1,4 +1,4 @@ -package com.baeldung.string.searching; +package com.baeldung.searching; import java.util.ArrayList; import java.util.List; diff --git a/java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/stopwords/RemovingStopwordsPerformanceComparison.java similarity index 82% rename from java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/stopwords/RemovingStopwordsPerformanceComparison.java index 5b455459cd..7df64de3f1 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/stopwords/RemovingStopwordsPerformanceComparison.java @@ -1,4 +1,6 @@ -package com.baeldung.string.performance; +package com.baeldung.stopwords; + +import org.openjdk.jmh.annotations.*; import java.io.IOException; import java.nio.file.Files; @@ -9,15 +11,6 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; - @Fork(value = 3, warmups = 1) @State(Scope.Benchmark) diff --git a/java-strings-2/src/main/resources/english_stopwords.txt b/core-java-modules/core-java-string-algorithms/src/main/resources/english_stopwords.txt similarity index 100% rename from java-strings-2/src/main/resources/english_stopwords.txt rename to core-java-modules/core-java-string-algorithms/src/main/resources/english_stopwords.txt diff --git a/java-strings-2/src/main/resources/shakespeare-hamlet.txt b/core-java-modules/core-java-string-algorithms/src/main/resources/shakespeare-hamlet.txt similarity index 100% rename from java-strings-2/src/main/resources/shakespeare-hamlet.txt rename to core-java-modules/core-java-string-algorithms/src/main/resources/shakespeare-hamlet.txt diff --git a/java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/countingchars/CountCharsExampleUnitTest.java similarity index 98% rename from java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/countingchars/CountCharsExampleUnitTest.java index d58684445b..8a5f1181b5 100644 --- a/java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/countingchars/CountCharsExampleUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.countingChars; +package com.baeldung.countingchars; import static org.junit.Assert.assertEquals; diff --git a/java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/matchwords/MatchWordsUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/matchwords/MatchWordsUnitTest.java index 385aadaa5d..9ff1066a12 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/matchwords/MatchWordsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.matchwords; import org.junit.Test; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/palindrom/PalindromeUnitTest.java similarity index 98% rename from java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/palindrom/PalindromeUnitTest.java index 8dea72d8ca..43334ad0fd 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/palindrom/PalindromeUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.palindrom; import static org.junit.Assert.assertTrue; diff --git a/java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/pangram/PangramUnitTest.java similarity index 97% rename from java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/pangram/PangramUnitTest.java index 36e603b535..b081a425e2 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/pangram/PangramUnitTest.java @@ -1,8 +1,9 @@ -package com.baeldung.string; +package com.baeldung.pangram; + +import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; public class PangramUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/removeduplicates/RemoveDuplicateFromStringUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/removeduplicates/RemoveDuplicateFromStringUnitTest.java index 895ecc4a3b..2372a5e569 100644 --- a/java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/removeduplicates/RemoveDuplicateFromStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.stringduplicates; +package com.baeldung.removeduplicates; import org.junit.Assert; import org.junit.Before; diff --git a/java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/removeemojis/RemovingEmojiFromStringUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/removeemojis/RemovingEmojiFromStringUnitTest.java index 8688f9dcf5..2c5f83400e 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/removeemojis/RemovingEmojiFromStringUnitTest.java @@ -1,13 +1,12 @@ -package com.baeldung.string; +package com.baeldung.removeemojis; -import static org.junit.Assert.assertEquals; +import com.vdurmont.emoji.EmojiParser; +import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.junit.Test; - -import com.vdurmont.emoji.EmojiParser; +import static org.junit.Assert.assertEquals; public class RemovingEmojiFromStringUnitTest { String text = "la conférence, commencera à 10 heures 😅"; diff --git a/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/repetition/SubstringRepetitionUnitTest.java similarity index 93% rename from java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/repetition/SubstringRepetitionUnitTest.java index f382a24a7f..5ecb7315c2 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/repetition/SubstringRepetitionUnitTest.java @@ -1,10 +1,10 @@ -package com.baeldung.string.repetition; - -import static com.baeldung.string.repetition.SubstringRepetition.*; -import static org.junit.Assert.*; +package com.baeldung.repetition; import org.junit.Test; +import static com.baeldung.repetition.SubstringRepetition.*; +import static org.junit.Assert.*; + public class SubstringRepetitionUnitTest { private String validString = "aa"; diff --git a/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java index 020ead02db..c122163174 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.reverse; +package com.baeldung.reverse; import org.apache.commons.lang3.StringUtils; import org.junit.Test; diff --git a/java-strings/src/test/java/com/baeldung/string/searching/WordIndexerUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/searching/WordIndexerUnitTest.java similarity index 98% rename from java-strings/src/test/java/com/baeldung/string/searching/WordIndexerUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/searching/WordIndexerUnitTest.java index f3f76db01f..774d5a2121 100644 --- a/java-strings/src/test/java/com/baeldung/string/searching/WordIndexerUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/searching/WordIndexerUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.searching; +package com.baeldung.searching; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/java-strings-2/src/test/java/com/baeldung/string/RemoveStopwordsUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/stopwords/RemoveStopwordsUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/RemoveStopwordsUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/stopwords/RemoveStopwordsUnitTest.java index edda2ec9d7..d90a70a9f5 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/RemoveStopwordsUnitTest.java +++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/stopwords/RemoveStopwordsUnitTest.java @@ -1,6 +1,7 @@ -package com.baeldung.string; +package com.baeldung.stopwords; -import static org.junit.Assert.assertEquals; +import org.junit.BeforeClass; +import org.junit.Test; import java.io.IOException; import java.nio.file.Files; @@ -10,8 +11,7 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class RemoveStopwordsUnitTest { final String original = "The quick brown fox jumps over the lazy dog"; diff --git a/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringUnitTest.java similarity index 96% rename from java-strings/src/test/java/com/baeldung/string/StringUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringUnitTest.java index 0d4fd6eff9..5c1fe2fbda 100644 --- a/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringUnitTest.java @@ -1,16 +1,13 @@ -package com.baeldung.string; +package com.baeldung.stringapi; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.Test; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.IllegalFormatException; import java.util.regex.PatternSyntaxException; -import org.junit.Test; +import static org.junit.Assert.*; public class StringUnitTest { diff --git a/core-java-modules/core-java-string-conversions-2/README.md b/core-java-modules/core-java-string-conversions-2/README.md index b4da1b8bad..afdd7e5760 100644 --- a/core-java-modules/core-java-string-conversions-2/README.md +++ b/core-java-modules/core-java-string-conversions-2/README.md @@ -5,5 +5,5 @@ This module contains articles about string conversions from/to another type. ### Relevant Articles: - [Java String Conversions](https://www.baeldung.com/java-string-conversions) - [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Convert Char Array to String](https://www.baeldung.com/java-char-array-to-string) +- [Convert Character Array to String in Java](https://www.baeldung.com/java-char-array-to-string) - More articles: [[<-- prev]](/core-java-string-conversions) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md new file mode 100644 index 0000000000..50f40ac2af --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -0,0 +1,11 @@ +## Java String Operations + +This module contains articles about string operations. + +### Relevant Articles: +- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) +- [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) +- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case) +- [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase) +- More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml new file mode 100644 index 0000000000..95aeec8fcb --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -0,0 +1,81 @@ + + 4.0.0 + core-java-string-operations-2 + 0.1.0-SNAPSHOT + jar + core-java-string-operations-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + javax.validation + validation-api + ${validation-api.version} + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish.web + javax.el + ${javax.el.version} + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-string-operations-2 + + + src/main/resources + true + + + + + + 3.6.1 + 2.0.0.Final + 3.8.1 + 27.0.1-jre + 6.0.2.Final + 3.0.0 + 2.2.6 + + + diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/EmptyStringCheck.java similarity index 75% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/EmptyStringCheck.java index 6d3234a4ec..85689eff99 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/EmptyStringCheck.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; class EmptyStringCheck { diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/Java5EmptyStringCheck.java similarity index 76% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/Java5EmptyStringCheck.java index 096b83acea..0c7997c075 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/Java5EmptyStringCheck.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; class Java5EmptyStringCheck { diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/PlainJavaBlankStringCheck.java similarity index 77% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/PlainJavaBlankStringCheck.java index 26e281c9b7..315ce4613a 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/PlainJavaBlankStringCheck.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; class PlainJavaBlankStringCheck { diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java similarity index 87% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java index 8c484efb43..058d53ba82 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; import javax.validation.constraints.Pattern; diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToLowerCaseUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToLowerCaseUnitTest.java index c395b61068..4826ba2ef7 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToLowerCaseUnitTest.java @@ -1,29 +1,29 @@ -package com.baeldung.string.changecase; - -import static org.junit.Assert.assertEquals; - -import java.util.Locale; - -import org.junit.Test; - -public class ToLowerCaseUnitTest { - - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignUppercase = "\u0049"; - - @Test - public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { - assertEquals("john doe", name.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { - assertEquals("\u0069", foreignUppercase.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { - assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); - } -} +package com.baeldung.changecase; + +import org.junit.Test; + +import java.util.Locale; + +import static org.junit.Assert.assertEquals; + +public class ToLowerCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0049"; + + @Test + public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { + assertEquals("john doe", name.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { + assertEquals("\u0069", foreignUppercase.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { + assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToUpperCaseUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToUpperCaseUnitTest.java index 1807f854b2..ab740f19b1 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToUpperCaseUnitTest.java @@ -1,29 +1,29 @@ -package com.baeldung.string.changecase; - -import static org.junit.Assert.assertEquals; - -import java.util.Locale; - -import org.junit.Test; - -public class ToUpperCaseUnitTest { - - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignLowercase = "\u0069"; - - @Test - public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { - assertEquals("JOHN DOE", name.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { - assertEquals("\u0049", foreignLowercase.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { - assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH)); - } -} +package com.baeldung.changecase; + +import org.junit.Test; + +import java.util.Locale; + +import static org.junit.Assert.assertEquals; + +public class ToUpperCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignLowercase = "\u0069"; + + @Test + public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { + assertEquals("JOHN DOE", name.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { + assertEquals("\u0049", foreignLowercase.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { + assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java similarity index 96% rename from java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java index 96b1d681dd..d772c38341 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java @@ -1,21 +1,17 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; -import static org.hamcrest.Matchers.iterableWithSize; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Set; +import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; +import java.util.Set; -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; - -import com.google.common.base.Strings; +import static org.hamcrest.Matchers.iterableWithSize; +import static org.junit.Assert.*; public class EmptyStringsUnitTest { diff --git a/java-strings-3/src/test/java/com/baeldung/string/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java similarity index 94% rename from java-strings-3/src/test/java/com/baeldung/string/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java index 5aab63db94..14fbf20c1d 100644 --- a/java-strings-3/src/test/java/com/baeldung/string/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.equalsIgnoreCase; +package com.baeldung.equalsIgnoreCase; import org.apache.commons.lang3.StringUtils; import org.junit.Test; diff --git a/java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java index 50d9a2b058..02beaa690a 100644 --- a/java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java @@ -1,11 +1,9 @@ package com.baeldung.initialization; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; - import org.junit.Test; +import static org.junit.Assert.*; + public class StringInitializationUnitTest { private String fieldString; diff --git a/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/stringconcatenation/StringConcatenationUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/stringconcatenation/StringConcatenationUnitTest.java index c25d4ce8f9..9a444e8229 100644 --- a/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/stringconcatenation/StringConcatenationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.stringconcatenation; import org.junit.Test; diff --git a/core-java-modules/core-java-string-operations/README.md b/core-java-modules/core-java-string-operations/README.md new file mode 100644 index 0000000000..18a2649a6a --- /dev/null +++ b/core-java-modules/core-java-string-operations/README.md @@ -0,0 +1,16 @@ +## Java String Operations + +This module contains articles about string operations. + +### Relevant Articles: +- [Comparing Strings in Java](https://www.baeldung.com/java-compare-strings) +- [Check If a String Is Numeric in Java](https://www.baeldung.com/java-check-string-number) +- [Get Substring from String in Java](https://www.baeldung.com/java-substring) +- [Split a String in Java](https://www.baeldung.com/java-split-string) +- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Java toString() Method](https://www.baeldung.com/java-tostring) +- [String Operations with Java Streams](https://www.baeldung.com/java-stream-operations-on-strings) +- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) +- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) +- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) +- More articles: [[next -->]](../core-java-string-operations-2) diff --git a/java-strings/pom.xml b/core-java-modules/core-java-string-operations/pom.xml old mode 100755 new mode 100644 similarity index 51% rename from java-strings/pom.xml rename to core-java-modules/core-java-string-operations/pom.xml index 42a57bfb42..fdddd99433 --- a/java-strings/pom.xml +++ b/core-java-modules/core-java-string-operations/pom.xml @@ -1,117 +1,66 @@ 4.0.0 - com.baeldung - java-strings + core-java-string-operations 0.1.0-SNAPSHOT jar - java-strings + core-java-string-operations com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java - - commons-io - commons-io - ${commons-io.version} - org.apache.commons commons-lang3 ${commons-lang3.version} - - log4j - log4j - ${log4j.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - - org.assertj - assertj-core - ${assertj.version} - test - org.openjdk.jmh jmh-core ${jmh-core.version} + + log4j + log4j + ${log4j.version} + org.openjdk.jmh jmh-generator-annprocess ${jmh-generator.version} - com.ibm.icu - icu4j - ${icu4j.version} + commons-codec + commons-codec + ${commons-codec.version} - com.google.guava - guava - ${guava.version} - - - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter-api.version} + org.assertj + assertj-core + ${assertj.version} test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - java-strings + core-java-string-operations src/main/resources true - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - 3.8.1 - 1.10 - 3.6.1 - 61.1 - 27.0.1-jre - 5.3.1 - 1.4 + 1.10 diff --git a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/Benchmarking.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/Benchmarking.java similarity index 98% rename from java-strings-ops/src/main/java/com/baeldung/string/isnumeric/Benchmarking.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/Benchmarking.java index c4e2742da6..97e7a46757 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/Benchmarking.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/Benchmarking.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import java.util.concurrent.TimeUnit; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/CheckIntegerInput.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/CheckIntegerInput.java similarity index 92% rename from java-strings-ops/src/main/java/com/baeldung/string/isnumeric/CheckIntegerInput.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/CheckIntegerInput.java index 2785df0c9b..6c08615c74 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/CheckIntegerInput.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/CheckIntegerInput.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import java.util.Scanner; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/IsNumeric.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumeric.java similarity index 96% rename from java-strings-ops/src/main/java/com/baeldung/string/isnumeric/IsNumeric.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumeric.java index 508cedd168..6eed0d777d 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/IsNumeric.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumeric.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/IsNumericDriver.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumericDriver.java similarity index 96% rename from java-strings-ops/src/main/java/com/baeldung/string/isnumeric/IsNumericDriver.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumericDriver.java index bb3c96c06e..a6c5449696 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/isnumeric/IsNumericDriver.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumericDriver.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import org.apache.log4j.Logger; diff --git a/java-strings/src/main/java/com/baeldung/string/newline/AddingNewLineToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java similarity index 98% rename from java-strings/src/main/java/com/baeldung/string/newline/AddingNewLineToString.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java index 48b71eed12..f701ab2e45 100644 --- a/java-strings/src/main/java/com/baeldung/string/newline/AddingNewLineToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java @@ -1,4 +1,4 @@ -package com.baeldung.string.newline; +package com.baeldung.newline; public class AddingNewLineToString { diff --git a/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/streamoperations/JoinerSplitter.java similarity index 96% rename from java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/streamoperations/JoinerSplitter.java index cdbba1ef53..8a105188ad 100644 --- a/java-strings/src/main/java/com/baeldung/string/JoinerSplitter.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/streamoperations/JoinerSplitter.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.streamoperations; import java.util.Arrays; import java.util.List; diff --git a/java-strings-2/src/main/java/com/baeldung/string/search/performance/SubstringSearchPerformanceComparison.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/substringsearch/SubstringSearchPerformanceComparison.java similarity index 79% rename from java-strings-2/src/main/java/com/baeldung/string/search/performance/SubstringSearchPerformanceComparison.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/substringsearch/SubstringSearchPerformanceComparison.java index bf33c47a7e..92aef0b879 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/search/performance/SubstringSearchPerformanceComparison.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/substringsearch/SubstringSearchPerformanceComparison.java @@ -1,18 +1,11 @@ -package com.baeldung.string.search.performance; +package com.baeldung.substringsearch; + +import org.apache.commons.lang3.StringUtils; +import org.openjdk.jmh.annotations.*; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; -import org.apache.commons.lang3.StringUtils; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; - /** * Based on https://github.com/tedyoung/indexof-contains-benchmark */ diff --git a/java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/Customer.java similarity index 91% rename from java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/Customer.java index 7ab3936cb9..16e2b05a7c 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/Customer.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class Customer { private String firstName; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerArrayToString.java similarity index 92% rename from java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerArrayToString.java index 391ced61d3..c942f978da 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerArrayToString.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import java.util.Arrays; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerComplexObjectToString.java similarity index 91% rename from java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerComplexObjectToString.java index ae3d999b12..3ca11779c4 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerComplexObjectToString.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class CustomerComplexObjectToString extends Customer { private Order order; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerPrimitiveToString.java similarity index 91% rename from java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerPrimitiveToString.java index 01fe4c8b09..38555aa236 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerPrimitiveToString.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class CustomerPrimitiveToString extends Customer { private long balance; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerReflectionToString.java similarity index 95% rename from java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerReflectionToString.java index 2a9e3700ec..ad0c57351a 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerReflectionToString.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import java.util.List; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerWrapperCollectionToString.java similarity index 95% rename from java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerWrapperCollectionToString.java index b3ff97dc07..7b7d9e4e7d 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/CustomerWrapperCollectionToString.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import java.util.List; diff --git a/java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/Order.java similarity index 95% rename from java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/Order.java index 58e0fcce5a..85a5dd169f 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/tostring/Order.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class Order { diff --git a/java-strings-ops/src/main/resources/log4j.properties b/core-java-modules/core-java-string-operations/src/main/resources/log4j.properties similarity index 100% rename from java-strings-ops/src/main/resources/log4j.properties rename to core-java-modules/core-java-string-operations/src/main/resources/log4j.properties diff --git a/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/ApacheCommonsEncodeDecodeUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/base64encodinganddecoding/ApacheCommonsEncodeDecodeUnitTest.java similarity index 100% rename from java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/ApacheCommonsEncodeDecodeUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/base64encodinganddecoding/ApacheCommonsEncodeDecodeUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/Java8EncodeDecodeUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/base64encodinganddecoding/Java8EncodeDecodeUnitTest.java similarity index 100% rename from java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/Java8EncodeDecodeUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/base64encodinganddecoding/Java8EncodeDecodeUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java similarity index 99% rename from java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java index e2bb7bb64d..6f8a17e316 100644 --- a/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java @@ -1,16 +1,15 @@ package com.baeldung.base64encodinganddecoding; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; +import javax.xml.bind.DatatypeConverter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; -import javax.xml.bind.DatatypeConverter; - -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class StringToByteArrayUnitTest { diff --git a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/CoreJavaIsNumericUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/CoreJavaIsNumericUnitTest.java similarity index 95% rename from java-strings-ops/src/test/java/com/baeldung/string/isnumeric/CoreJavaIsNumericUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/CoreJavaIsNumericUnitTest.java index 6228fdb5af..6c03b00e69 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/CoreJavaIsNumericUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/CoreJavaIsNumericUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/NumberUtilsIsCreatableUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsCreatableUnitTest.java similarity index 96% rename from java-strings-ops/src/test/java/com/baeldung/string/isnumeric/NumberUtilsIsCreatableUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsCreatableUnitTest.java index 346248cb40..3b88721ad4 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/NumberUtilsIsCreatableUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsCreatableUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/NumberUtilsIsParsableUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsParsableUnitTest.java similarity index 96% rename from java-strings-ops/src/test/java/com/baeldung/string/isnumeric/NumberUtilsIsParsableUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsParsableUnitTest.java index fa2f2aec6d..6b96a6efa1 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/NumberUtilsIsParsableUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsParsableUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/RegularExpressionsUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/RegularExpressionsUnitTest.java similarity index 93% rename from java-strings-ops/src/test/java/com/baeldung/string/isnumeric/RegularExpressionsUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/RegularExpressionsUnitTest.java index 0f7f0eb081..04f3de8dc5 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/RegularExpressionsUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/RegularExpressionsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/StringUtilsIsNumericSpaceUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericSpaceUnitTest.java similarity index 95% rename from java-strings-ops/src/test/java/com/baeldung/string/isnumeric/StringUtilsIsNumericSpaceUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericSpaceUnitTest.java index 05651cc567..0c5e52580f 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/StringUtilsIsNumericSpaceUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericSpaceUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/StringUtilsIsNumericUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericUnitTest.java similarity index 95% rename from java-strings-ops/src/test/java/com/baeldung/string/isnumeric/StringUtilsIsNumericUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericUnitTest.java index cae08874da..660426cdbb 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/isnumeric/StringUtilsIsNumericUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.isnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/split/SplitUnitTest.java similarity index 98% rename from java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/split/SplitUnitTest.java index 1936bfb6fb..eaa61e5041 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/split/SplitUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.split; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/streamoperations/JoinerSplitterUnitTest.java similarity index 98% rename from java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/streamoperations/JoinerSplitterUnitTest.java index a9488e27a4..2a0f03d3a8 100644 --- a/java-strings/src/test/java/com/baeldung/string/JoinerSplitterUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/streamoperations/JoinerSplitterUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.streamoperations; import org.junit.Test; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/stringcomparison/StringComparisonUnitTest.java similarity index 99% rename from java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/stringcomparison/StringComparisonUnitTest.java index 5339a0c72e..0bab708fde 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/stringcomparison/StringComparisonUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.stringcomparison; import static org.assertj.core.api.Assertions.assertThat; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/substring/SubstringUnitTest.java similarity index 98% rename from java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/substring/SubstringUnitTest.java index eb397f2a3f..00340ba7cc 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/substring/SubstringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.substring; import java.util.Scanner; import java.util.regex.Matcher; diff --git a/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/substringsearch/SubstringSearchUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/substringsearch/SubstringSearchUnitTest.java index 293e6d2125..c641ccbe07 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/substringsearch/SubstringSearchUnitTest.java @@ -1,12 +1,12 @@ -package com.baeldung.string.search; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; +package com.baeldung.substringsearch; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * BAEL-2832: Different ways to check if a Substring could be found in a String. */ diff --git a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerArrayToStringUnitTest.java similarity index 95% rename from java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerArrayToStringUnitTest.java index ced8b15f2e..a754ed3c68 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerArrayToStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerComplexObjectToStringUnitTest.java similarity index 95% rename from java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerComplexObjectToStringUnitTest.java index 564fde8766..1b26d3e0a2 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerComplexObjectToStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerPrimitiveToStringUnitTest.java similarity index 94% rename from java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerPrimitiveToStringUnitTest.java index f585a8a26c..a21ab1616f 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerPrimitiveToStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerWrapperCollectionToStringUnitTest.java similarity index 96% rename from java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerWrapperCollectionToStringUnitTest.java index 9b3f8a1a6f..da4937ccdd 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerWrapperCollectionToStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md new file mode 100644 index 0000000000..4a418db29f --- /dev/null +++ b/core-java-modules/core-java-strings/README.md @@ -0,0 +1,14 @@ +## Java Strings + +This module contains articles about strings in Java. + +### Relevant Articles: +- [Use char[] Array over a String for Manipulating Passwords in Java?](https://www.baeldung.com/java-storing-passwords) +- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string) +- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) +- [String Performance Hints](https://www.baeldung.com/java-string-performance) +- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) +- [Java – Generate Random String](https://www.baeldung.com/java-random-string) +- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) +- [Java Multi-line String](https://www.baeldung.com/java-multiline-string) +- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) diff --git a/core-java-modules/core-java-strings/pom.xml b/core-java-modules/core-java-strings/pom.xml new file mode 100644 index 0000000000..6a80886549 --- /dev/null +++ b/core-java-modules/core-java-strings/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + core-java-strings + 0.1.0-SNAPSHOT + jar + core-java-strings + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + com.ibm.icu + icu4j + ${icu4j.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-strings + + + src/main/resources + true + + + + + + 3.6.1 + 61.1 + + + diff --git a/java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java similarity index 97% rename from java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java index cb24511f72..eae75eaa2b 100644 --- a/java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java @@ -1,9 +1,10 @@ package com.baeldung.java9.compactstring; import java.util.List; -import static java.util.stream.Collectors.toList; import java.util.stream.IntStream; +import static java.util.stream.Collectors.toList; + public class CompactStringDemo { public static void main(String[] args) { @@ -11,14 +12,14 @@ public class CompactStringDemo { List strings = IntStream.rangeClosed(1, 10_000_000) .mapToObj(Integer::toString).collect(toList()); long totalTime = System.currentTimeMillis() - startTime; - System.out.println("Generated " + strings.size() + " strings in " + System.out.println("Generated " + strings.size() + " strings in " + totalTime + " ms."); startTime = System.currentTimeMillis(); String appended = (String) strings.stream().limit(100_000) .reduce("", (left, right) -> left.toString() + right.toString()); totalTime = System.currentTimeMillis() - startTime; - System.out.println("Created string of length " + appended.length() + System.out.println("Created string of length " + appended.length() + " in " + totalTime + " ms."); } } diff --git a/java-strings-2/src/main/java/com/baeldung/localization/App.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/App.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/App.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/App.java diff --git a/java-strings-2/src/main/java/com/baeldung/localization/ICUFormat.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/ICUFormat.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/ICUFormat.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/ICUFormat.java index f7bc357933..c82af30c87 100644 --- a/java-strings-2/src/main/java/com/baeldung/localization/ICUFormat.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/ICUFormat.java @@ -1,11 +1,11 @@ package com.baeldung.localization; +import com.ibm.icu.text.MessageFormat; + import java.util.List; import java.util.Locale; import java.util.ResourceBundle; -import com.ibm.icu.text.MessageFormat; - public class ICUFormat { public static String getLabel(Locale locale, Object[] data) { diff --git a/java-strings-2/src/main/java/com/baeldung/localization/JavaSEFormat.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/JavaSEFormat.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/JavaSEFormat.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/JavaSEFormat.java diff --git a/java-strings-2/src/main/java/com/baeldung/localization/Localization.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/Localization.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/Localization.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/Localization.java diff --git a/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/multiline/MultiLineString.java similarity index 98% rename from java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/multiline/MultiLineString.java index 1bde2dcb63..987bc751cd 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/multiline/MultiLineString.java @@ -1,4 +1,7 @@ -package com.baeldung.string.multiline; +package com.baeldung.multiline; + +import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; import java.io.IOException; import java.io.PrintWriter; @@ -6,9 +9,6 @@ import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Paths; -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableList; - public class MultiLineString { String newLine = System.getProperty("line.separator"); diff --git a/java-strings/src/main/java/com/baeldung/string/StringPerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringperformance/StringPerformance.java similarity index 99% rename from java-strings/src/main/java/com/baeldung/string/StringPerformance.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/stringperformance/StringPerformance.java index 3b0c32991c..8e9d3afdde 100644 --- a/java-strings/src/main/java/com/baeldung/string/StringPerformance.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringperformance/StringPerformance.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.stringperformance; import com.google.common.base.Splitter; import org.apache.commons.lang3.StringUtils; diff --git a/java-strings-2/src/main/resources/formats_en.properties b/core-java-modules/core-java-strings/src/main/resources/formats_en.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_en.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_en.properties diff --git a/java-strings-2/src/main/resources/formats_fr.properties b/core-java-modules/core-java-strings/src/main/resources/formats_fr.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_fr.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_fr.properties diff --git a/java-strings-2/src/main/resources/formats_it.properties b/core-java-modules/core-java-strings/src/main/resources/formats_it.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_it.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_it.properties diff --git a/java-strings-2/src/main/resources/formats_pl.properties b/core-java-modules/core-java-strings/src/main/resources/formats_pl.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_pl.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_pl.properties diff --git a/java-streams/src/main/resources/logback.xml b/core-java-modules/core-java-strings/src/main/resources/logback.xml similarity index 100% rename from java-streams/src/main/resources/logback.xml rename to core-java-modules/core-java-strings/src/main/resources/logback.xml diff --git a/java-strings-2/src/main/resources/messages_en.properties b/core-java-modules/core-java-strings/src/main/resources/messages_en.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_en.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_en.properties diff --git a/java-strings-2/src/main/resources/messages_fr.properties b/core-java-modules/core-java-strings/src/main/resources/messages_fr.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_fr.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_fr.properties diff --git a/java-strings-2/src/main/resources/messages_it.properties b/core-java-modules/core-java-strings/src/main/resources/messages_it.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_it.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_it.properties diff --git a/java-strings-2/src/main/resources/messages_pl.properties b/core-java-modules/core-java-strings/src/main/resources/messages_pl.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_pl.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_pl.properties diff --git a/java-strings-2/src/main/resources/stephenking.txt b/core-java-modules/core-java-strings/src/main/resources/stephenking.txt similarity index 100% rename from java-strings-2/src/main/resources/stephenking.txt rename to core-java-modules/core-java-strings/src/main/resources/stephenking.txt diff --git a/java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/LocaleUnitTest.java similarity index 93% rename from java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/LocaleUnitTest.java index 1d221056fd..5655d2536d 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/LocaleUnitTest.java @@ -1,11 +1,12 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; + +import org.junit.Test; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Locale; -import static org.junit.Assert.assertEquals; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class LocaleUnitTest { @Test diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringAnagramUnitTest.java similarity index 94% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringAnagramUnitTest.java index aadfade737..8f3bacc267 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringAnagramUnitTest.java @@ -1,10 +1,10 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; import java.util.Arrays; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; public class StringAnagramUnitTest { public boolean isAnagram(String s1, String s2) { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringChangeCaseUnitTest.java similarity index 92% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringChangeCaseUnitTest.java index 2c7ec500fe..4c3815a2e4 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringChangeCaseUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringChangeCaseUnitTest { @Test public void givenString_whenChangingToUppercase_thenCaseChanged() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringCountOccurrencesUnitTest.java similarity index 94% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringCountOccurrencesUnitTest.java index 6c17643ac8..cb92c06d32 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringCountOccurrencesUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringCountOccurrencesUnitTest { public int countOccurrences(String s, char c) { int count = 0; diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringFormatUnitTest.java similarity index 90% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringFormatUnitTest.java index 787017791c..8492db0dc0 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringFormatUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringFormatUnitTest { @Test public void givenString_whenUsingStringFormat_thenStringFormatted() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringInternUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringInternUnitTest.java index c5bffb7573..3092a72399 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringInternUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.assertj.core.api.Assertions.assertThat; +package com.baeldung.interview; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class StringInternUnitTest { @Test public void whenCallingStringIntern_thenStringsInterned() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringJoinerUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringJoinerUnitTest.java index d44c7478e4..b5556f588c 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringJoinerUnitTest.java @@ -1,10 +1,11 @@ -package com.baeldung.string.interview; - -import java.util.StringJoiner; -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import java.util.StringJoiner; + +import static org.junit.Assert.assertEquals; + public class StringJoinerUnitTest { @Test public void whenUsingStringJoiner_thenStringsJoined() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringPalindromeUnitTest.java similarity index 95% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringPalindromeUnitTest.java index 79ed14cd99..760939932a 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringPalindromeUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.assertj.core.api.Assertions.assertThat; +package com.baeldung.interview; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class StringPalindromeUnitTest { public boolean isPalindrome(String text) { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringReverseUnitTest.java similarity index 88% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringReverseUnitTest.java index bb9b45dc97..484a6d0d68 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringReverseUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringReverseUnitTest { @Test public void whenUsingInbuildMethods_thenStringReversed() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringSplitUnitTest.java similarity index 95% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringSplitUnitTest.java index e1cea62462..5aff593e3e 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringSplitUnitTest.java @@ -1,7 +1,8 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; import org.apache.commons.lang3.StringUtils; import org.junit.Test; + import static org.junit.Assert.assertArrayEquals; public class StringSplitUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToByteArrayUnitTest.java similarity index 95% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToByteArrayUnitTest.java index aee4eedcd6..90c5ca25c2 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToByteArrayUnitTest.java @@ -1,11 +1,11 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; -import static org.junit.Assert.assertArrayEquals; +import org.junit.Test; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; -import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; public class StringToByteArrayUnitTest { @Test diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToCharArrayUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToCharArrayUnitTest.java index 1322d0fa82..5ebd7448f1 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToCharArrayUnitTest.java @@ -1,10 +1,10 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.Arrays; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class StringToCharArrayUnitTest { @Test diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToIntegerUnitTest.java similarity index 89% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToIntegerUnitTest.java index a905438a84..24a715dc75 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToIntegerUnitTest.java @@ -1,6 +1,7 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; import org.junit.Test; + import static org.assertj.core.api.Assertions.assertThat; public class StringToIntegerUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java index 2c8f9b47f3..3c5c5fcb55 100644 --- a/java-strings-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java @@ -1,12 +1,10 @@ package com.baeldung.localization; -import static org.junit.Assert.assertEquals; - -import java.util.Locale; - import org.junit.Test; -import com.baeldung.localization.ICUFormat; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; public class ICUFormatUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/multiline/MultiLineStringUnitTest.java similarity index 85% rename from java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/multiline/MultiLineStringUnitTest.java index 3ebee9b5d1..04d318c71b 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/multiline/MultiLineStringUnitTest.java @@ -1,11 +1,10 @@ -package com.baeldung.string.multiline; +package com.baeldung.multiline; import org.junit.Test; -import static org.junit.Assert.assertEquals; import java.io.IOException; -import com.baeldung.string.multiline.MultiLineString; +import static org.junit.Assert.assertEquals; public class MultiLineStringUnitTest { diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java new file mode 100644 index 0000000000..2806635d03 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.randomstrings; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.charset.Charset; +import java.util.Random; + +public class RandomStringsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class); + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { + final byte[] array = new byte[7]; // length is bounded by 7 + new Random().nextBytes(array); + final String generatedString = new String(array, Charset.forName("UTF-8")); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { + final int leftLimit = 97; // letter 'a' + final int rightLimit = 122; // letter 'z' + final int targetStringLength = 10; + final Random random = new Random(); + final StringBuilder buffer = new StringBuilder(targetStringLength); + + for (int i = 0; i < targetStringLength; i++) { + final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); + buffer.append((char) randomLimitedInt); + } + final String generatedString = buffer.toString(); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { + final String generatedString = RandomStringUtils.random(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { + final String generatedString = RandomStringUtils.randomAlphabetic(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { + final String generatedString = RandomStringUtils.randomAlphanumeric(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { + final int length = 10; + final boolean useLetters = true; + final boolean useNumbers = false; + final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); + + LOG.debug(generatedString); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringnotempty/StringNotEmptyUnitTest.java similarity index 81% rename from java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/stringnotempty/StringNotEmptyUnitTest.java index 17b13f89de..482105cc40 100644 --- a/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringnotempty/StringNotEmptyUnitTest.java @@ -1,21 +1,16 @@ -package com.baeldung.string; - -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; -import static org.hamcrest.text.IsEmptyString.isEmptyString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +package com.baeldung.stringnotempty; +import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; import org.junit.Test; -import com.google.common.base.Strings; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; +import static org.hamcrest.text.IsEmptyString.isEmptyString; +import static org.junit.Assert.*; -public class StringEmptyUnitTest { +public class StringNotEmptyUnitTest { private String text = "baeldung"; diff --git a/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java similarity index 100% rename from java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java diff --git a/core-java-modules/core-java-time-measurements/README.md b/core-java-modules/core-java-time-measurements/README.md new file mode 100644 index 0000000000..1bd277b6b1 --- /dev/null +++ b/core-java-modules/core-java-time-measurements/README.md @@ -0,0 +1,8 @@ +## Java Time Measurements + +This module contains articles about the measurement of time in Java. + +### Relevant Articles: +- [Guide to the Java Clock Class](http://www.baeldung.com/java-clock) +- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) +- [Overriding System Time for Testing in Java](https://www.baeldung.com/java-override-system-time) diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml new file mode 100644 index 0000000000..0ff3787051 --- /dev/null +++ b/core-java-modules/core-java-time-measurements/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + com.baeldung.exception.numberformat + core-java-time-measurements + 0.0.1-SNAPSHOT + jar + core-java-time-measurements + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + joda-time + joda-time + ${joda.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + org.jmockit + jmockit + ${jmockit.version} + test + + + + + core-java-time-measurements + + + src/main/resources + true + + + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar + + true + + + + + + + + 3.6.1 + 2.10 + + 3.6.1 + 1.8.9 + 2.0.0-RC.4 + 1.44 + + 2.22.1 + + diff --git a/java-strings-2/src/main/resources/logback.xml b/core-java-modules/core-java-time-measurements/src/main/resources/logback.xml similarity index 100% rename from java-strings-2/src/main/resources/logback.xml rename to core-java-modules/core-java-time-measurements/src/main/resources/logback.xml diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/java/clock/ClockUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/java/clock/ClockUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index 436a481803..c65428c6af 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -1,19 +1,13 @@ -========= - ## Core Java Cookbooks and Examples ### Relevant Articles: - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) -- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) -- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) - [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) - [Getting Started with Java Properties](http://www.baeldung.com/java-properties) -- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) - [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) -- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend) - [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) @@ -24,16 +18,12 @@ - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) -- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os) - [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) - [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) -- [Class Loaders in Java](http://www.baeldung.com/java-classloaders) -- [Guide to the Java Clock Class](http://www.baeldung.com/java-clock) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) - [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) - [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) -- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation) - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) @@ -41,7 +31,7 @@ - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) - [Graphs in Java](https://www.baeldung.com/java-graphs) -- [Console I/O in Java](http://www.baeldung.com/java-console-input-output) +- [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output) - [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) - [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) - [Introduction to Basic Syntax in Java](https://www.baeldung.com/java-syntax) diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 392bcaa6dc..9d4bee081e 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -60,24 +60,6 @@ moneta ${javamoney.moneta.version} - - org.owasp.esapi - esapi - ${esapi.version} - - - - org.javassist - javassist - ${javaassist.version} - - - com.sun - tools - ${sun.tools.version} - system - ${java.home}/../lib/tools.jar - @@ -401,24 +383,18 @@ 0.4 1.8.7 - + 3.10.0 - + 1.1 - 2.1.0.1 - + 3.0.0-M1 3.0.2 1.4.4 3.1.1 2.0.3.RELEASE 1.6.0 - - - 3.21.0-GA - - 1.8.0 diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/README.md deleted file mode 100644 index 7b3b40c102..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 68ece1c473..16ec19835a 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -19,6 +19,7 @@ core-java-lang-operators core-java-networking-2 core-java-security-manager + core-java-date-operations diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md index ecf16c2c91..06dda396d9 100644 --- a/core-kotlin-2/README.md +++ b/core-kotlin-2/README.md @@ -12,4 +12,5 @@ This module contains articles about core Kotlin. - [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) - [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) - [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations) +- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) - More articles: [[<-- prev]](/core-kotlin) diff --git a/ethereum/pom.xml b/ethereum/pom.xml index f4850df844..148909e787 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.ethereum ethereum @@ -215,5 +215,4 @@ 1.7.25 2.0.4.RELEASE - diff --git a/gradle-5/README.md b/gradle-5/README.md index 73b6b7e12a..7c9aeff07e 100644 --- a/gradle-5/README.md +++ b/gradle-5/README.md @@ -1,5 +1,3 @@ - ### Relevant Articles: - [Run a Java main Method Using Gradle](https://www.baeldung.com/gradle-run-java-main) - diff --git a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java index 004314b0ed..c8910878a9 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -13,7 +13,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppConfig.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppConfig.class) public class SpringAndHystrixIntegrationTest { @Autowired diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/MyBean.java b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/MyBean.java index 5d4ce4202c..e4e78ce445 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/MyBean.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/MyBean.java @@ -1,8 +1,10 @@ package com.baeldung.jackson.annotation; +import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonSetter; @JsonInclude(Include.NON_NULL) @JsonPropertyOrder({ "name", "id" }) @@ -18,4 +20,14 @@ public class MyBean { this.id = id; this.name = name; } + + @JsonGetter("name") + public String getTheName() { + return name; + } + + @JsonSetter("name") + public void setTheName(String name) { + this.name = name; + } } diff --git a/java-collections-conversions-2/README.md b/java-collections-conversions-2/README.md new file mode 100644 index 0000000000..761e56253e --- /dev/null +++ b/java-collections-conversions-2/README.md @@ -0,0 +1,7 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about conversions among Collection types and arrays in Java. + +### Relevant Articles: +- [Array to String Conversions](https://www.baeldung.com/java-array-to-string) +- More articles: [[<-- prev]](../java-collections-conversions) \ No newline at end of file diff --git a/java-collections-conversions-2/pom.xml b/java-collections-conversions-2/pom.xml new file mode 100644 index 0000000000..72673527ac --- /dev/null +++ b/java-collections-conversions-2/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + java-collections-conversions-2 + 0.1.0-SNAPSHOT + java-collections-conversions-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + java-collections-conversions-2 + + + src/main/resources + true + + + + + + + diff --git a/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java similarity index 98% rename from java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java rename to java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java index b563475997..73cf9d6baa 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java +++ b/java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java @@ -1,15 +1,14 @@ -package org.baeldung.convertarraytostring; +package com.baeldung.convertarraytostring; + +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; - -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; - import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index 6d4f6ddb3a..2d3aa41f2d 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -9,8 +9,8 @@ This module contains articles about conversions among Collection types and array - [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set) - [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string) - [How to Convert List to Map in Java](https://www.baeldung.com/java-list-to-map) -- [Array to String Conversions](https://www.baeldung.com/java-array-to-string) - [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) - [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap) - [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection) - [Converting Iterator to List](https://www.baeldung.com/java-convert-iterator-to-list) +- More articles: [[next -->]](../java-collections-conversions-2) \ No newline at end of file diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index 24d918d105..b5ab4f841a 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -32,6 +32,16 @@ + + java-collections-conversions-2 + + + src/main/resources + true + + + + 4.1 3.6.1 diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java similarity index 97% rename from java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java index 1de600aebf..ad2ab2a756 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java @@ -14,10 +14,10 @@ import static org.junit.Assert.*; * * @author chris */ -public class FooUnitTest { +public class CollectionToArrayListUnitTest { private static Collection srcCollection = new HashSet<>(); - public FooUnitTest() { + public CollectionToArrayListUnitTest() { } @BeforeClass diff --git a/java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java similarity index 98% rename from java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java index ced2ddcfc0..4d6cba7d27 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.convert.iteratortolist; +package com.baeldung.convertiteratortolist; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java similarity index 96% rename from java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java index 6e766433d1..5e6828a3d5 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java @@ -11,7 +11,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; -public class ConvertListWithDiplicatedIdToMapServiceUnitTest { +public class ConvertListWithDuplicatedIdToMapServiceUnitTest { List duplicatedIdList; private ConvertListToMapService convertListService = new ConvertListToMapService(); diff --git a/java-collections-conversions/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java similarity index 99% rename from java-collections-conversions/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java index a5f684a141..4977c122e7 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.collections; +package com.baeldung.java.collections; import java.util.ArrayList; import java.util.Arrays; diff --git a/java-collections-conversions/src/test/java/org/baeldung/java/lists/ListToSTring.java b/java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java similarity index 91% rename from java-collections-conversions/src/test/java/org/baeldung/java/lists/ListToSTring.java rename to java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java index 3fc26bcb51..0fdc096d14 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/java/lists/ListToSTring.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.lists; +package com.baeldung.java.lists; import java.util.Arrays; import java.util.List; @@ -7,7 +7,7 @@ import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.junit.Test; -public class ListToSTring { +public class ListToStringUnitTest { @Test public void whenListToString_thenPrintDefault() { diff --git a/java-collections-maps-2/README.md b/java-collections-maps-2/README.md index 0db83fbae7..8b33276f56 100644 --- a/java-collections-maps-2/README.md +++ b/java-collections-maps-2/README.md @@ -5,7 +5,7 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives) - [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap) -- [Guide to Java HashMap]() +- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap) - [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) - [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map) diff --git a/java-collections-maps/README.md b/java-collections-maps/README.md index 87fefe1b9d..dfd0d47dbc 100644 --- a/java-collections-maps/README.md +++ b/java-collections-maps/README.md @@ -4,7 +4,7 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) -- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap) +- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) - [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) - [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) @@ -13,4 +13,5 @@ This module contains articles about Map data structures in Java. - [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) - [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) - [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map) +- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced) - More articles: [[next -->]](/../java-collections-maps-2) diff --git a/java-dates-2/src/main/java/com/baeldung/date/conversion/ConvertToOffsetDateTime.java b/java-dates-2/src/main/java/com/baeldung/date/conversion/ConvertToOffsetDateTime.java new file mode 100644 index 0000000000..34914962f9 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/conversion/ConvertToOffsetDateTime.java @@ -0,0 +1,19 @@ +package com.baeldung.date.conversion; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Date; + +public class ConvertToOffsetDateTime { + + public static OffsetDateTime convert(Date date) { + return date.toInstant() + .atOffset(ZoneOffset.UTC); + } + + public static OffsetDateTime convert(Date date, int hour, int minute) { + return date.toInstant() + .atOffset(ZoneOffset.ofHoursMinutes(hour, minute)); + } + +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/conversion/ConvertToOffsetDateTimeUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/conversion/ConvertToOffsetDateTimeUnitTest.java new file mode 100644 index 0000000000..c927da00c8 --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/conversion/ConvertToOffsetDateTimeUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.date.conversion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.time.OffsetDateTime; +import java.util.Date; + +import org.junit.Test; + +public class ConvertToOffsetDateTimeUnitTest { + + @Test + public void whenDateIsNotNull_thenConvertToOffsetDateTime() { + Date date = new Date(); + assertTrue(ConvertToOffsetDateTime.convert(date) instanceof OffsetDateTime); + } + + @Test + public void givenDate_whenHasOffset_thenConvertWithOffset() { + Date date = new Date(); + date.setHours(6); + date.setMinutes(30); + OffsetDateTime odt = ConvertToOffsetDateTime.convert(date, 3, 30); + assertEquals(10, odt.getHour()); + assertEquals(0, odt.getMinute()); + } + +} diff --git a/java-dates/README.md b/java-dates/README.md deleted file mode 100644 index d4657a3057..0000000000 --- a/java-dates/README.md +++ /dev/null @@ -1,24 +0,0 @@ -========= - -## Java Dates Cookbooks and Examples - -### Relevant Articles: -- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) -- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) -- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) -- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) -- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) -- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) -- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) -- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) -- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) -- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) -- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) -- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) -- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) -- [Calculate Age in Java](http://www.baeldung.com/java-get-age) -- [Increment Date in Java](http://www.baeldung.com/java-increment-date) -- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) -- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) -- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) -- [Introduction to Joda-Time](https://www.baeldung.com/joda-time) diff --git a/java-dates/src/main/java/com/baeldung/datetime/README.md b/java-dates/src/main/java/com/baeldung/datetime/README.md deleted file mode 100644 index 7d843af9ea..0000000000 --- a/java-dates/src/main/java/com/baeldung/datetime/README.md +++ /dev/null @@ -1 +0,0 @@ -### Relevant Articles: diff --git a/java-dates/src/test/resources/.gitignore b/java-dates/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-dates/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java b/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java index 2273dfda13..de37b8d1e3 100644 --- a/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java +++ b/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java @@ -1,12 +1,10 @@ package com.baeldung.random; -import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.nio.charset.Charset; import java.util.Random; public class JavaRandomUnitTest { @@ -155,63 +153,4 @@ public class JavaRandomUnitTest { LOG.debug("{}", generatedDouble); } - // tests - random String - - @Test - public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { - final byte[] array = new byte[7]; // length is bounded by 7 - new Random().nextBytes(array); - final String generatedString = new String(array, Charset.forName("UTF-8")); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { - final int leftLimit = 97; // letter 'a' - final int rightLimit = 122; // letter 'z' - final int targetStringLength = 10; - final Random random = new Random(); - final StringBuilder buffer = new StringBuilder(targetStringLength); - - for (int i = 0; i < targetStringLength; i++) { - final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); - buffer.append((char) randomLimitedInt); - } - final String generatedString = buffer.toString(); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { - final String generatedString = RandomStringUtils.random(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { - final String generatedString = RandomStringUtils.randomAlphabetic(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { - final String generatedString = RandomStringUtils.randomAlphanumeric(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { - final int length = 10; - final boolean useLetters = true; - final boolean useNumbers = false; - final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); - - LOG.debug(generatedString); - } - } diff --git a/java-streams-2/README.md b/java-streams-2/README.md deleted file mode 100644 index 66fbe69ed4..0000000000 --- a/java-streams-2/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Java Streams Cookbooks and Examples - -This module contains articles about the Stream API in Java. - -### Relevant Articles: -- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) -- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) -- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) -- More articles: [[<-- prev]](/java-streams) diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java b/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java deleted file mode 100644 index a17c6a02b6..0000000000 --- a/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.reduce.entities; - -public class User { - - private final String name; - private final int age; - - public User(String name, int age) { - this.name = name; - this.age = age; - } - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - @Override - public String toString() { - return "User{" + "name=" + name + ", age=" + age + '}'; - } -} diff --git a/java-streams/.gitignore b/java-streams/.gitignore deleted file mode 100644 index 3de4cc647e..0000000000 --- a/java-streams/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/java-streams/README.md b/java-streams/README.md deleted file mode 100644 index a57fdec7fa..0000000000 --- a/java-streams/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Java Streams Cookbooks and Examples - -This module contains articles about the Stream API in Java. - -### Relevant Articles: -- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams) -- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction) -- [Java 8 and Infinite Streams](https://www.baeldung.com/java-inifinite-streams) -- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany) -- [How to Get the Last Element of a Stream in Java?](https://www.baeldung.com/java-stream-last-element) -- [“Stream has already been operated upon or closed” Exception in Java](https://www.baeldung.com/java-stream-operated-upon-or-closed-exception) -- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream) -- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices) -- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) -- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) -- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) -- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) -- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) -- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api) -- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams) -- More articles: [[next -->]](/java-streams-2) diff --git a/java-streams/pom.xml b/java-streams/pom.xml deleted file mode 100644 index bd0123e01d..0000000000 --- a/java-streams/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - 4.0.0 - java-streams - 0.1.0-SNAPSHOT - java-streams - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator.version} - provided - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - log4j - log4j - ${log4j.version} - - - org.projectlombok - lombok - ${lombok.version} - provided - - - - org.assertj - assertj-core - ${assertj.version} - test - - - com.codepoetics - protonpack - ${protonpack.version} - - - io.vavr - vavr - ${vavr.version} - - - one.util - streamex - ${streamex.version} - - - org.aspectj - aspectjrt - ${asspectj.version} - - - org.aspectj - aspectjweaver - ${asspectj.version} - - - pl.touk - throwing-function - ${throwing-function.version} - - - - - java-streams - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - -parameters - - - - - - - - 0.9.0 - 1.15 - 0.6.5 - 2.10 - 1.3 - - 3.11.1 - 1.8.9 - 3.1 - 1.8 - 1.8 - - diff --git a/java-streams/src/main/java/com/baeldung/reduce/application/Application.java b/java-streams/src/main/java/com/baeldung/reduce/application/Application.java deleted file mode 100644 index b101c86780..0000000000 --- a/java-streams/src/main/java/com/baeldung/reduce/application/Application.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.reduce.application; - -import com.baeldung.reduce.entities.User; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.Warmup; - -public class Application { - - public static void main(String[] args) throws Exception { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); - System.out.println(result1); - - int result2 = numbers.stream().reduce(0, Integer::sum); - System.out.println(result2); - - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); - System.out.println(result3); - - String result4 = letters.stream().reduce("", String::concat); - System.out.println(result4); - - String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); - System.out.println(result5); - - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result6); - - String result7 = letters.parallelStream().reduce("", String::concat); - System.out.println(result7); - - int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result8); - - org.openjdk.jmh.Main.main(args); - - } - - @Benchmark - @Fork(value = 1, warmups = 2) - @Warmup(iterations = 2) - @BenchmarkMode(Mode.AverageTime) - public void executeReduceOnParallelizedStream() { - List userList = new ArrayList<>(); - for (int i = 0; i <= 1000000; i++) { - userList.add(new User("John" + i, i)); - } - userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } - - @Benchmark - @Fork(value = 1, warmups = 2) - @Warmup(iterations = 2) - @BenchmarkMode(Mode.AverageTime) - public void executeReduceOnSequentialStream() { - List userList = new ArrayList<>(); - for (int i = 0; i <= 1000000; i++) { - userList.add(new User("John" + i, i)); - } - userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } -} diff --git a/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java b/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java deleted file mode 100644 index 8b4af2cbe2..0000000000 --- a/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.reduce.utilities; - -import java.util.List; -import java.util.function.BiFunction; -import java.util.logging.Level; -import java.util.logging.Logger; - -public abstract class NumberUtils { - - private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); - - public static int divideListElements(List values, Integer divider) { - return values.stream() - .reduce(0, (a, b) -> { - try { - return a / divider + b / divider; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return 0; - }); - } - - public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { - return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); - } - - public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { - BiFunction division = (a, b) -> a / b; - return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); - } - - private static int divide(int value, int factor) { - int result = 0; - try { - result = value / factor; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return result; - } - - private static int applyFunction(BiFunction function, int a, int b) { - try { - return function.apply(a, b); - } - catch(Exception e) { - LOGGER.log(Level.INFO, "Exception occurred!"); - } - return 0; - } -} diff --git a/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java b/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java deleted file mode 100644 index 8e2ff7bf22..0000000000 --- a/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.reduce.tests; - -import com.baeldung.reduce.entities.User; -import com.baeldung.reduce.utilities.NumberUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class StreamReduceUnitTest { - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, (a, b) -> a + b); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, Integer::sum); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (a, b) -> a + b); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase()); - assertThat(result).isEqualTo("ABCDE"); - } - - @Test - public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - assertThat(result).isEqualTo(65); - } - - @Test - public void givenStringList_whenReduceWithParallelStream_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.parallelStream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); - } -} diff --git a/java-streams/src/test/resources/.gitignore b/java-streams/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-streams/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-2/README.md b/java-strings-2/README.md deleted file mode 100644 index ced813163d..0000000000 --- a/java-strings-2/README.md +++ /dev/null @@ -1,27 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about strings in Java. - -### Relevant Articles: - -- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) -- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) -- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) -- [Java – Generate Random String](https://www.baeldung.com/java-random-string) -- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) -- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) -- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) -- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) -- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) -- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) -- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) -- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) -- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) -- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) -- [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings) -- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) -- [Java Multi-line String](https://www.baeldung.com/java-multiline-string) -- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) -- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string) -- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case) -- More articles: [[<-- prev>]](/java-strings) [[next -->]](/java-strings-3) diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml deleted file mode 100755 index be47b1ec89..0000000000 --- a/java-strings-2/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - 4.0.0 - java-strings-2 - 0.1.0-SNAPSHOT - jar - java-strings-2 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-core.version} - - - com.ibm.icu - icu4j - ${icu4j.version} - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - commons-io - commons-io - ${commons-io.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - org.passay - passay - ${passay.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - com.vdurmont - emoji-java - ${emoji-java.version} - - - org.ahocorasick - ahocorasick - ${ahocorasick.version} - - - javax.validation - validation-api - ${validation-api.version} - - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - - - - - java-strings-2 - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - - - - 3.8.1 - 1.10 - 1.3.1 - - 3.6.1 - 4.0.0 - 0.4.0 - 61.1 - 28.0-jre - 1.4 - 2.0.0.Final - 6.0.2.Final - 3.0.0 - 2.2.6 - - - \ No newline at end of file diff --git a/java-strings-2/src/test/resources/.gitignore b/java-strings-2/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-2/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-3/README.md b/java-strings-3/README.md deleted file mode 100644 index 6276dfc621..0000000000 --- a/java-strings-3/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about strings in Java. - -### Relevant Articles: -- [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase) -- [Finding the Difference Between Two Strings](https://www.baeldung.com/java-difference-between-two-strings) -- [Counting Words in a String](https://www.baeldung.com/java-word-counting) -- More articles: [[<-- prev>]](/java-strings-2) diff --git a/java-strings-3/pom.xml b/java-strings-3/pom.xml deleted file mode 100644 index 4589780c15..0000000000 --- a/java-strings-3/pom.xml +++ /dev/null @@ -1,161 +0,0 @@ - - 4.0.0 - java-strings-3 - 0.1.0-SNAPSHOT - jar - java-strings-3 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-core.version} - - - com.ibm.icu - icu4j - ${icu4j.version} - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - commons-io - commons-io - ${commons-io.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.bitbucket.cowwoc - diff-match-patch - 1.2 - test - - - - - org.passay - passay - ${passay.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - com.vdurmont - emoji-java - ${emoji-java.version} - - - org.ahocorasick - ahocorasick - ${ahocorasick.version} - - - javax.validation - validation-api - ${validation-api.version} - - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - - - - - java-strings-3 - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - - - - 3.8.1 - 1.10 - 1.3.1 - - 3.6.1 - 4.0.0 - 0.4.0 - 61.1 - 28.0-jre - 1.4 - 2.0.0.Final - 6.0.2.Final - 3.0.0 - 2.2.6 - - - \ No newline at end of file diff --git a/java-strings-3/src/main/resources/.gitignore b/java-strings-3/src/main/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-3/src/main/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-3/src/test/resources/.gitignore b/java-strings-3/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-3/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-ops/README.md b/java-strings-ops/README.md deleted file mode 100644 index 1300cf028e..0000000000 --- a/java-strings-ops/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about operations on strings in Java. - -### Relevant Articles: -- [Check If a String Is a Palindrome](https://www.baeldung.com/java-palindrome) -- [Comparing Strings in Java](https://www.baeldung.com/java-compare-strings) -- [Check If a String Is Numeric in Java](https://www.baeldung.com/java-check-string-number) -- [Get Substring from String in Java](https://www.baeldung.com/java-substring) -- [How to Remove the Last Character of a String?](https://www.baeldung.com/java-remove-last-character-of-string) -- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) -- [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars) -- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) -- [Split a String in Java](https://www.baeldung.com/java-split-string) -- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) -- [Java toString() Method](https://www.baeldung.com/java-tostring) diff --git a/java-strings-ops/src/test/resources/.gitignore b/java-strings-ops/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-ops/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings/README.md b/java-strings/README.md deleted file mode 100644 index 17b74231a4..0000000000 --- a/java-strings/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about strings in Java. - -### Relevant Articles: -- [String Operations with Java Streams](https://www.baeldung.com/java-stream-operations-on-strings) -- [Use char[] Array Over a String for Manipulating Passwords in Java?](https://www.baeldung.com/java-storing-passwords) -- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string) -- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) -- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) -- [String Performance Hints](https://www.baeldung.com/java-string-performance) -- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) -- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) -- [Remove or Replace Part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) -- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) -- More articles: [[next -->]](/java-strings-2) diff --git a/java-strings/src/main/resources/data.csv b/java-strings/src/main/resources/data.csv deleted file mode 100644 index ec4ac10443..0000000000 --- a/java-strings/src/main/resources/data.csv +++ /dev/null @@ -1,3 +0,0 @@ -1|IND|India -2|MY|Malaysia -3|AU|Australia diff --git a/java-strings/src/main/resources/logback.xml b/java-strings/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/java-strings/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java deleted file mode 100644 index 3488f8b390..0000000000 --- a/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class CharArrayToStringUnitTest { - - @Test - public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = new String(charArray); - String expectedValue = "character"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = new String(charArray, 4, 3); - String expectedValue = "act"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.copyValueOf(charArray); - String expectedValue = "character"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.copyValueOf(charArray, 0, 4); - String expectedValue = "char"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.valueOf(charArray); - String expectedValue = "character"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.valueOf(charArray, 3, 4); - String expectedValue = "ract"; - - assertEquals(expectedValue, result); - } -} diff --git a/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java deleted file mode 100644 index cd996e58e2..0000000000 --- a/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class StringToCharArrayUnitTest { - - @Test - public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { - String givenString = "characters"; - - char[] result = givenString.toCharArray(); - - char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; - - assertArrayEquals(expectedCharArray, result); - } - -} diff --git a/java-strings/src/test/resources/.gitignore b/java-strings/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/javaxval/README.md b/javaxval/README.md index c2c392b276..33ce4eae5b 100644 --- a/javaxval/README.md +++ b/javaxval/README.md @@ -9,4 +9,4 @@ This module contains articles about Bean Validation. - [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank) - [Javax BigDecimal Validation](https://www.baeldung.com/javax-bigdecimal-validation) - [Grouping Javax Validation Constraints](https://www.baeldung.com/javax-validation-groups) -- [Javax Validations for Enums](https://www.baeldung.com/javax-validations-enums) +- [Validations for Enum Types](https://www.baeldung.com/javax-validations-enums) diff --git a/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java b/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java new file mode 100644 index 0000000000..b9fcfdf4d4 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java @@ -0,0 +1,42 @@ +package org.baeldung.javaxval.messageinterpolator; + +import javax.validation.constraints.Email; +import javax.validation.constraints.Min; +import javax.validation.constraints.Size; + +public class Person { + + @Size(min = 10, max = 100, message = "Name should be between {min} and {max} characters") + private String name; + + @Min(value = 18, message = "Age should not be less than {value}") + private int age; + + @Email(message = "Email address should be in a correct format: ${validatedValue}") + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java b/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java new file mode 100644 index 0000000000..6ecb916ab4 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java @@ -0,0 +1,70 @@ +package org.baeldung.javaxval.messageinterpolator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ParameterMessageInterpolaterIntegrationTest { + + private static Validator validator; + + @BeforeClass + public static void beforeClass() { + ValidatorFactory validatorFactory = Validation.byDefaultProvider() + .configure() + .messageInterpolator(new ParameterMessageInterpolator()) + .buildValidatorFactory(); + + validator = validatorFactory.getValidator(); + } + + @Test + public void givenNameLengthLessThanMin_whenValidate_thenValidationFails() { + Person person = new Person(); + person.setName("John Doe"); + person.setAge(18); + + Set> violations = validator.validate(person); + assertEquals(1, violations.size()); + + ConstraintViolation violation = violations.iterator().next(); + assertEquals("Name should be between 10 and 100 characters", violation.getMessage()); + } + + @Test + public void givenAgeIsLessThanMin_whenValidate_thenValidationFails() { + Person person = new Person(); + person.setName("John Stephaner Doe"); + person.setAge(16); + + Set> violations = validator.validate(person); + assertEquals(1, violations.size()); + + ConstraintViolation violation = violations.iterator().next(); + assertEquals("Age should not be less than 18", violation.getMessage()); + } + + @Test + public void givenEmailIsMalformed_whenValidate_thenValidationFails() { + Person person = new Person(); + person.setName("John Stephaner Doe"); + person.setAge(18); + person.setEmail("johndoe.dev"); + + Set> violations = validator.validate(person); + assertEquals(1, violations.size()); + + ConstraintViolation violation = violations.iterator().next(); + assertEquals("Email address should be in a correct format: ${validatedValue}", violation.getMessage()); + } + +} diff --git a/jaxb/README.md b/jaxb/README.md index d9d16ab70b..a471ccd39d 100644 --- a/jaxb/README.md +++ b/jaxb/README.md @@ -5,4 +5,3 @@ This module contains articles about JAXB. ### Relevant Articles: - [Guide to JAXB](https://www.baeldung.com/jaxb) - [Unmarshalling Dates Using JAXB](https://www.baeldung.com/jaxb-unmarshalling-dates) - diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml index 17163ba23c..60765f6bc2 100644 --- a/jee-kotlin/pom.xml +++ b/jee-kotlin/pom.xml @@ -230,7 +230,7 @@ - wildfly-remote-arquillian + wildfly-remote-arquillian-disabled org.jboss.resteasy diff --git a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java index b91b47cb1f..d48a3a96da 100644 --- a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java +++ b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java @@ -36,7 +36,7 @@ public class StudentResourceIntegrationTest { .withMavenCentralRepo(true) .withClassPathResolution(true) .loadPomFromFile("pom.xml") - .resolve("org.jetbrains.kotlin:kotlin-stdlib") + .resolve("org.jetbrains.kotlin:kotlin-stdlib:1.3.41") .withTransitivity() .as(JavaArchive.class); diff --git a/jersey/README.md b/jersey/README.md index 8537e07358..366e7665f3 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -10,4 +10,3 @@ This module contains articles about Jersey. - [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test) - [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters) - [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers) - diff --git a/jhipster-5/README.md b/jhipster-5/README.md index ba05641af0..e4a6b3c3a0 100644 --- a/jhipster-5/README.md +++ b/jhipster-5/README.md @@ -1,3 +1,6 @@ ## JHipster 5 This module contains articles about JHipster 5. This is an aggregator module, articles are in the relevant submodules. + +### Relevant Articles: +- [JHipster Authentication with an External Service](https://www.baeldung.com/jhipster-authentication-external-service) diff --git a/jta/pom.xml b/jta/pom.xml index b7e39c66e1..1e86a0144c 100644 --- a/jta/pom.xml +++ b/jta/pom.xml @@ -30,12 +30,6 @@ spring-boot-starter - - org.springframework.boot - spring-boot-starter-test - test - - org.hsqldb hsqldb diff --git a/libraries-2/README.md b/libraries-2/README.md index fd1f73c386..95c454edbb 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -18,6 +18,7 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map) - [Guide to MapDB](https://www.baeldung.com/mapdb) - [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos) -- [JasperReports with Spring](https://www.baeldung.com/spring-jasper) +- [JasperReports with Spring](https://www.baeldung.com/spring-jasper)] +- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) - More articles [[<-- prev]](/libraries) diff --git a/libraries-3/README.md b/libraries-3/README.md new file mode 100644 index 0000000000..a6c6b190ab --- /dev/null +++ b/libraries-3/README.md @@ -0,0 +1,9 @@ +## Libraries-3 + +This module contains articles about various Java libraries. +These are small libraries that are relatively easy to use and do not require any separate module of their own. + +The code examples related to different libraries are each in their own module. + +Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. + diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml new file mode 100644 index 0000000000..214e87287d --- /dev/null +++ b/libraries-3/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + libraries-3 + libraries-3 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + jboss-public-repository-group + JBoss Public Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + + true + never + + + true + daily + + + + + + + com.beust + jcommander + ${jcommander.version} + + + org.projectlombok + lombok + ${lombok.version} + + + + + 1.78 + 1.18.6 + UTF-8 + 1.8 + 1.8 + + diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java b/libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java new file mode 100644 index 0000000000..56a74ecf21 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java @@ -0,0 +1,37 @@ +package com.baeldung.jcommander.helloworld; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; + +public class HelloWorldApp { + + /* + * Execute: + * mvn exec:java -Dexec.mainClass=com.baeldung.jcommander.helloworld.HelloWorldApp -q \ + * -Dexec.args="--name JavaWorld" + */ + public static void main(String[] args) { + HelloWorldArgs jArgs = new HelloWorldArgs(); + JCommander helloCmd = JCommander + .newBuilder() + .addObject(jArgs) + .build(); + + helloCmd.parse(args); + System.out.println("Hello " + jArgs.getName()); + } +} + +class HelloWorldArgs { + + @Parameter( + names = "--name", + description = "User name", + required = true + ) + private String name; + + public String getName() { + return name; + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java new file mode 100644 index 0000000000..029e7eed01 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java @@ -0,0 +1,23 @@ +package com.baeldung.jcommander.usagebilling; + +import com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling; + +public class UsageBasedBillingApp { + + /* + * Entry-point: invokes the cli passing the command-line args + * + * Invoking "Submit" sub-command: + * mvn exec:java \ + -Dexec.mainClass=com.baeldung.jcommander.usagebilling.UsageBasedBillingApp -q \ + -Dexec.args="submit --customer cb898e7a-f2a0-46d2-9a09-531f1cee1839 --subscription subscriptionPQRMN001 --pricing-type PRE_RATED --timestamp 2019-10-03T10:58:00 --quantity 7 --price 24.56" + * + * Invoking "Fetch" sub-command: + * mvn exec:java \ + -Dexec.mainClass=com.baeldung.jcommander.usagebilling.UsageBasedBillingApp -q \ + -Dexec.args="fetch --customer cb898e7a-f2a0-46d2-9a09-531f1cee1839 --subscription subscriptionPQRMN001 subscriptionPQRMN002 subscriptionPQRMN003 --itemized" + */ + public static void main(String[] args) { + new UsageBasedBilling().run(args); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java new file mode 100644 index 0000000000..ea6b18af53 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java @@ -0,0 +1,67 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.baeldung.jcommander.usagebilling.cli.splitter.ColonParameterSplitter; +import com.baeldung.jcommander.usagebilling.cli.validator.UUIDValidator; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; +import com.baeldung.jcommander.usagebilling.service.FetchCurrentChargesService; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import lombok.Getter; + +import java.util.List; + +import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.*; +import static com.baeldung.jcommander.usagebilling.service.FetchCurrentChargesService.getDefault; + +@Parameters( + commandNames = { FETCH_CMD }, + commandDescription = "Fetch charges for a customer in the current month, can be itemized or aggregated" +) +@Getter +class FetchCurrentChargesCommand { + + FetchCurrentChargesCommand() { + } + + private FetchCurrentChargesService service = getDefault(); + + @Parameter(names = "--help", help = true) + private boolean help; + + @Parameter( + names = { "--customer", "-C" }, + description = "Id of the Customer who's using the services", + validateWith = UUIDValidator.class, + order = 1, + required = true + ) + private String customerId; + + @Parameter( + names = { "--subscription", "-S" }, + description = "Filter charges for specific subscription Ids, includes all subscriptions if no value is specified", + variableArity = true, + splitter = ColonParameterSplitter.class, + order = 2 + ) + private List subscriptionIds; + + @Parameter( + names = { "--itemized" }, + description = "Whether the response should contain breakdown by subscription, only aggregate values are returned by default", + order = 3 + ) + private boolean itemized; + + void fetch() { + CurrentChargesRequest req = CurrentChargesRequest.builder() + .customerId(customerId) + .subscriptionIds(subscriptionIds) + .itemized(itemized) + .build(); + + CurrentChargesResponse response = service.fetch(req); + System.out.println(response); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java new file mode 100644 index 0000000000..d3516b19d3 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java @@ -0,0 +1,96 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.baeldung.jcommander.usagebilling.cli.converter.ISO8601TimestampConverter; +import com.baeldung.jcommander.usagebilling.cli.validator.UUIDValidator; +import com.baeldung.jcommander.usagebilling.model.UsageRequest; +import com.baeldung.jcommander.usagebilling.model.UsageRequest.PricingType; +import com.baeldung.jcommander.usagebilling.service.SubmitUsageService; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import lombok.Getter; + +import java.math.BigDecimal; +import java.time.Instant; + +import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.*; +import static com.baeldung.jcommander.usagebilling.service.SubmitUsageService.getDefault; + +@Parameters( + commandNames = { SUBMIT_CMD }, + commandDescription = "Submit usage for a given customer and subscription, accepts one usage item" +) +@Getter +class SubmitUsageCommand { + + SubmitUsageCommand() { + } + + private SubmitUsageService service = getDefault(); + + @Parameter(names = "--help", help = true) + private boolean help; + + @Parameter( + names = { "--customer", "-C" }, + description = "Id of the Customer who's using the services", + validateWith = UUIDValidator.class, + order = 1, + required = true + ) + private String customerId; + + @Parameter( + names = { "--subscription", "-S" }, + description = "Id of the Subscription that was purchased", + order = 2, + required = true + ) + private String subscriptionId; + + @Parameter( + names = { "--pricing-type", "-P" }, + description = "Pricing type of the usage reported", + order = 3, + required = true + ) + private PricingType pricingType; + + @Parameter( + names = { "--quantity" }, + description = "Used quantity; reported quantity is added over the billing period", + order = 3, + required = true + ) + private Integer quantity; + + @Parameter( + names = { "--timestamp" }, + description = "Timestamp of the usage event, must lie in the current billing period", + converter = ISO8601TimestampConverter.class, + order = 4, + required = true + ) + private Instant timestamp; + + @Parameter( + names = { "--price" }, + description = "If PRE_RATED, unit price to be applied per unit of usage quantity reported", + order = 5 + ) + private BigDecimal price; + + void submit() { + + UsageRequest req = UsageRequest.builder() + .customerId(customerId) + .subscriptionId(subscriptionId) + .pricingType(pricingType) + .quantity(quantity) + .timestamp(timestamp) + .price(price) + .build(); + + String reqId = service.submit(req); + System.out.println("Generated Request Id for reference: " + reqId); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java new file mode 100644 index 0000000000..a531a68644 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java @@ -0,0 +1,80 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.UnixStyleUsageFormatter; + +public class UsageBasedBilling { + + static final String SUBMIT_CMD = "submit"; + static final String FETCH_CMD = "fetch"; + + private JCommander jCommander; + private SubmitUsageCommand submitUsageCmd; + private FetchCurrentChargesCommand fetchChargesCmd; + + public UsageBasedBilling() { + this.submitUsageCmd = new SubmitUsageCommand(); + this.fetchChargesCmd = new FetchCurrentChargesCommand(); + jCommander = JCommander.newBuilder() + .addObject(this) + .addCommand(submitUsageCmd) + .addCommand(fetchChargesCmd) + .build(); + + setUsageFormatter(SUBMIT_CMD); + setUsageFormatter(FETCH_CMD); + } + + public void run(String[] args) { + String parsedCmdStr; + try { + jCommander.parse(args); + parsedCmdStr = jCommander.getParsedCommand(); + + switch (parsedCmdStr) { + case SUBMIT_CMD: + if (submitUsageCmd.isHelp()) { + getSubCommandHandle(SUBMIT_CMD).usage(); + } + System.out.println("Parsing usage request..."); + submitUsageCmd.submit(); + break; + + case FETCH_CMD: + if (fetchChargesCmd.isHelp()) { + getSubCommandHandle(SUBMIT_CMD).usage(); + } + System.out.println("Preparing fetch query..."); + fetchChargesCmd.fetch(); + + break; + + default: + System.err.println("Invalid command: " + parsedCmdStr); + } + } catch (ParameterException e) { + System.err.println(e.getLocalizedMessage()); + parsedCmdStr = jCommander.getParsedCommand(); + if (parsedCmdStr != null) { + getSubCommandHandle(parsedCmdStr).usage(); + } else { + jCommander.usage(); + } + } + } + + private JCommander getSubCommandHandle(String command) { + JCommander cmd = jCommander.getCommands().get(command); + + if (cmd == null) { + System.err.println("Invalid command: " + command); + } + return cmd; + } + + private void setUsageFormatter(String subCommand) { + JCommander cmd = getSubCommandHandle(subCommand); + cmd.setUsageFormatter(new UnixStyleUsageFormatter(cmd)); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java new file mode 100644 index 0000000000..e54865a811 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java @@ -0,0 +1,33 @@ +package com.baeldung.jcommander.usagebilling.cli.converter; + +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.converters.BaseConverter; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +import static java.lang.String.format; + +public class ISO8601TimestampConverter extends BaseConverter { + + private static final DateTimeFormatter TS_FORMATTER = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss"); + + public ISO8601TimestampConverter(String optionName) { + super(optionName); + } + + @Override + public Instant convert(String value) { + try { + return LocalDateTime + .parse(value, TS_FORMATTER) + .atOffset(ZoneOffset.UTC) + .toInstant(); + } catch (DateTimeParseException e) { + throw new ParameterException(getErrorString(value, format("an ISO-8601 formatted timestamp (%s)", TS_FORMATTER.toString()))); + } + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java new file mode 100644 index 0000000000..f24c028123 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java @@ -0,0 +1,15 @@ +package com.baeldung.jcommander.usagebilling.cli.splitter; + +import com.beust.jcommander.converters.IParameterSplitter; + +import java.util.List; + +import static java.util.Arrays.asList; + +public class ColonParameterSplitter implements IParameterSplitter { + + @Override + public List split(String value) { + return asList(value.split(":")); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java new file mode 100644 index 0000000000..a72912f7d0 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java @@ -0,0 +1,26 @@ +package com.baeldung.jcommander.usagebilling.cli.validator; + +import com.beust.jcommander.IParameterValidator; +import com.beust.jcommander.ParameterException; + +import java.util.regex.Pattern; + +public class UUIDValidator implements IParameterValidator { + + private static final String UUID_REGEX = + "[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; + + @Override + public void validate(String name, String value) throws ParameterException { + if (!isValidUUID(value)) { + throw new ParameterException( + "String parameter " + value + " is not a valid UUID."); + } + } + + private boolean isValidUUID(String value) { + return Pattern + .compile(UUID_REGEX) + .matcher(value).matches(); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java new file mode 100644 index 0000000000..93dd7a5732 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java @@ -0,0 +1,16 @@ +package com.baeldung.jcommander.usagebilling.model; + +import lombok.*; + +import java.util.List; + +@NoArgsConstructor(access = AccessLevel.PACKAGE) +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@Builder +@Getter +public class CurrentChargesRequest { + + private String customerId; + private List subscriptionIds; + private boolean itemized; +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java new file mode 100644 index 0000000000..865a6e4a3d --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java @@ -0,0 +1,56 @@ +package com.baeldung.jcommander.usagebilling.model; + +import lombok.*; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; + +@NoArgsConstructor(access = AccessLevel.PACKAGE) +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@Builder +@Getter +public class CurrentChargesResponse { + + private String customerId; + private BigDecimal amountDue; + private List lineItems; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb + .append("Current Month Charges: {") + .append("\n\tcustomer: ") + .append(this.customerId) + .append("\n\ttotalAmountDue: ") + .append(this.amountDue.setScale(2, RoundingMode.HALF_UP)) + .append("\n\tlineItems: ["); + + for (LineItem li : this.lineItems) { + sb + .append("\n\t\t{") + .append("\n\t\t\tsubscription: ") + .append(li.subscriptionId) + .append("\n\t\t\tamount: ") + .append(li.amount.setScale(2, RoundingMode.HALF_UP)) + .append("\n\t\t\tquantity: ") + .append(li.quantity) + .append("\n\t\t},"); + } + + sb.append("\n\t]\n}\n"); + return sb.toString(); + } + + @NoArgsConstructor(access = AccessLevel.PACKAGE) + @AllArgsConstructor(access = AccessLevel.PACKAGE) + @Builder + @Getter + public static class LineItem { + + private String subscriptionId; + private BigDecimal amount; + private Integer quantity; + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java new file mode 100644 index 0000000000..2785474acf --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java @@ -0,0 +1,50 @@ +package com.baeldung.jcommander.usagebilling.model; + +import lombok.*; + +import java.math.BigDecimal; +import java.time.Instant; + +@NoArgsConstructor(access = AccessLevel.PACKAGE) +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@Builder +@Getter +public class UsageRequest { + + private String customerId; + private String subscriptionId; + private PricingType pricingType; + private Integer quantity; + private BigDecimal price; + private Instant timestamp; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb + .append("\nUsage: {") + .append("\n\tcustomer: ") + .append(this.customerId) + .append("\n\tsubscription: ") + .append(this.subscriptionId) + .append("\n\tquantity: ") + .append(this.quantity) + .append("\n\ttimestamp: ") + .append(this.timestamp) + .append("\n\tpricingType: ") + .append(this.pricingType); + + if (PricingType.PRE_RATED == this.pricingType) { + sb + .append("\n\tpreRatedAt: ") + .append(this.price); + } + + sb.append("\n}\n"); + return sb.toString(); + } + + public enum PricingType { + PRE_RATED, UNRATED + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java new file mode 100644 index 0000000000..6436d49875 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java @@ -0,0 +1,68 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse.LineItem; + +import java.math.BigDecimal; +import java.util.List; +import java.util.UUID; + +import static java.lang.String.format; +import static java.util.Arrays.asList; +import static java.util.Arrays.fill; +import static java.util.Collections.emptyList; +import static java.util.concurrent.ThreadLocalRandom.current; +import static java.util.stream.Collectors.toList; + +class DefaultFetchCurrentChargesService implements FetchCurrentChargesService { + + @Override + public CurrentChargesResponse fetch(CurrentChargesRequest request) { + List subscriptions = request.getSubscriptionIds(); + + if (subscriptions == null || subscriptions.isEmpty()) { + System.out.println("Fetching ALL charges for customer: " + request.getCustomerId()); + subscriptions = mockSubscriptions(); + + } else { + System.out.println(format("Fetching charges for customer: %s and subscriptions: %s", request.getCustomerId(), subscriptions)); + } + + CurrentChargesResponse charges = mockCharges(request.getCustomerId(), subscriptions, request.isItemized()); + System.out.println("Fetched charges..."); + return charges; + } + + private CurrentChargesResponse mockCharges(String customerId, List subscriptions, boolean itemized) { + List lineItems = mockLineItems(subscriptions); + BigDecimal amountDue = lineItems + .stream() + .map(li -> li.getAmount()) + .reduce(new BigDecimal("0"), BigDecimal::add); + + return CurrentChargesResponse + .builder() + .customerId(customerId) + .lineItems(itemized ? lineItems : emptyList()) + .amountDue(amountDue) + .build(); + } + + private List mockLineItems(List subscriptions) { + return subscriptions + .stream() + .map(subscription -> LineItem.builder() + .subscriptionId(subscription) + .quantity(current().nextInt(20)) + .amount(new BigDecimal(current().nextDouble(1_000))) + .build()) + .collect(toList()); + } + + private List mockSubscriptions() { + String[] subscriptions = new String[5]; + fill(subscriptions, UUID.randomUUID().toString()); + return asList(subscriptions); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java new file mode 100644 index 0000000000..44ac9e9ed7 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java @@ -0,0 +1,16 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.UsageRequest; + +import java.util.UUID; + +class DefaultSubmitUsageService implements SubmitUsageService { + + @Override + public String submit(UsageRequest request) { + System.out.println("Submitting usage..." + request); + + System.out.println("Submitted usage successfully..."); + return UUID.randomUUID().toString(); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java new file mode 100644 index 0000000000..2cc56658ff --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java @@ -0,0 +1,13 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; + +public interface FetchCurrentChargesService { + + static FetchCurrentChargesService getDefault() { + return new DefaultFetchCurrentChargesService(); + } + + CurrentChargesResponse fetch(CurrentChargesRequest request); +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java new file mode 100644 index 0000000000..2a29e6e474 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java @@ -0,0 +1,12 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.UsageRequest; + +public interface SubmitUsageService { + + static SubmitUsageService getDefault() { + return new DefaultSubmitUsageService(); + } + + String submit(UsageRequest request); +} diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java b/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java new file mode 100644 index 0000000000..48b3ac2896 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.jcommander.helloworld; + +import com.beust.jcommander.JCommander; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class HelloWorldAppUnitTest { + + @Test + public void whenJCommanderInvokedWithArgs_thenArgsParsed() { + + HelloWorldArgs jArgs = new HelloWorldArgs(); + JCommander helloCmd = JCommander + .newBuilder() + .addObject(jArgs) + .build(); + + // when + String[] argv = new String[] { + "--name", "JavaWorld" + }; + helloCmd.parse(argv); + + // then + assertEquals("JavaWorld", jArgs.getName()); + } +} diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java new file mode 100644 index 0000000000..b639661c39 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.beust.jcommander.JCommander; +import org.junit.Test; + +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertThat; + +public class FetchCurrentChargesCommandUnitTest { + + private JCommander jc = JCommander.newBuilder() + .addObject(new FetchCurrentChargesCommand()) + .build(); + + @Test + public void whenParsedMultipleSubscriptionsParameter_thenParameterSubscriptionsIsPopulated() { + FetchCurrentChargesCommand cmd = (FetchCurrentChargesCommand) jc + .getObjects() + .get(0); + + jc.parse(new String[] { + "-C", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "-S", "subscriptionA001", + "-S", "subscriptionA002", + "-S", "subscriptionA003", + }); + + assertThat(cmd.getSubscriptionIds(), + contains("subscriptionA001", "subscriptionA002", "subscriptionA003")); + } + + @Test + public void whenParsedSubscriptionsColonSeparatedParameter_thenParameterSubscriptionsIsPopulated() { + FetchCurrentChargesCommand cmd = (FetchCurrentChargesCommand) jc + .getObjects() + .get(0); + + jc.parse(new String[] { + "-C", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "-S", "subscriptionA001:subscriptionA002:subscriptionA003", + }); + + assertThat(cmd.getSubscriptionIds(), + contains("subscriptionA001", "subscriptionA002", "subscriptionA003")); + } + + @Test + public void whenParsedSubscriptionsWithVariableArity_thenParameterSubscriptionsIsPopulated() { + FetchCurrentChargesCommand cmd = (FetchCurrentChargesCommand) jc + .getObjects() + .get(0); + + jc.parse(new String[] { + "-C", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "-S", "subscriptionA001", "subscriptionA002", "subscriptionA003", + }); + + assertThat(cmd.getSubscriptionIds(), + contains("subscriptionA001", "subscriptionA002", "subscriptionA003")); + } +} diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java new file mode 100644 index 0000000000..d6ce132053 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.ParameterException; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SubmitUsageCommandUnitTest { + + private JCommander jc = JCommander.newBuilder() + .addObject(new SubmitUsageCommand()) + .build(); + + @Test + public void whenParsedCustomerParameter_thenParameterOfTypeStringIsPopulated() { + jc.parse(new String[] { + "--customer", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "--subscription", "subscriptionPQRMN001", + "--pricing-type", "PRE_RATED", + "--timestamp", "2019-10-03T10:58:00", + "--quantity", "7", + "--price", "24.56" + }); + + SubmitUsageCommand cmd = (SubmitUsageCommand) jc + .getObjects() + .get(0); + assertEquals("cb898e7a-f2a0-46d2-9a09-531f1cee1839", cmd.getCustomerId()); + } + + @Test + public void whenParsedTimestampParameter_thenParameterOfTypeInstantIsPopulated() { + jc.parse(new String[] { + "--customer", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "--subscription", "subscriptionPQRMN001", + "--pricing-type", "PRE_RATED", + "--timestamp", "2019-10-03T10:58:00", + "--quantity", "7", + "--price", "24.56" + }); + + SubmitUsageCommand cmd = (SubmitUsageCommand) jc + .getObjects() + .get(0); + assertEquals("2019-10-03T10:58:00Z", cmd + .getTimestamp() + .toString()); + } + + @Test(expected = ParameterException.class) + public void whenParsedCustomerIdNotUUID_thenParameterException() { + jc.parse(new String[] { + "--customer", "customer001", + "--subscription", "subscriptionPQRMN001", + "--pricing-type", "PRE_RATED", + "--timestamp", "2019-10-03T10:58:00", + "--quantity", "7", + "--price", "24.56" + }); + } +} diff --git a/libraries-data-io/src/main/resources/csv/twoColumn.csv b/libraries-data-io/src/main/resources/csv/twoColumn.csv new file mode 100644 index 0000000000..56d8fa1901 --- /dev/null +++ b/libraries-data-io/src/main/resources/csv/twoColumn.csv @@ -0,0 +1,5 @@ +colA, ColB +A, B +C, D +G, G +G, F \ No newline at end of file diff --git a/libraries-data-io/src/main/resources/csv/writtenAll.csv b/libraries-data-io/src/main/resources/csv/writtenAll.csv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries-data-io/src/main/resources/csv/writtenBean.csv b/libraries-data-io/src/main/resources/csv/writtenBean.csv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries-data-io/src/main/resources/csv/writtenOneByOne.csv b/libraries-data-io/src/main/resources/csv/writtenOneByOne.csv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries-primitive/README.MD b/libraries-primitive/README.MD index 086cdc0d2d..9cb89f3552 100644 --- a/libraries-primitive/README.MD +++ b/libraries-primitive/README.MD @@ -2,4 +2,3 @@ - [Guide to FastUtil](https://www.baeldung.com/fastutil) - [Primitive Collections in Eclipse Collections](https://www.baeldung.com/java-eclipse-primitive-collections) - diff --git a/libraries-security/README.md b/libraries-security/README.md index 68badcf12d..819bc866cf 100644 --- a/libraries-security/README.md +++ b/libraries-security/README.md @@ -9,3 +9,4 @@ This module contains articles about security libraries. - [Guide to Google Tink](https://www.baeldung.com/google-tink) - [Introduction to BouncyCastle with Java](https://www.baeldung.com/java-bouncy-castle) - [Intro to Jasypt](https://www.baeldung.com/jasypt) +- [Digital Signature in Java](https://www.baeldung.com/java-digital-signature) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index a2fbed31b2..86c9bd52e1 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -125,19 +125,6 @@ ${java-hamcrest.version} test - - - net.serenity-bdd - serenity-core - ${serenity.version} - test - - - org.asciidoctor - asciidoctorj - - - org.asciidoctor asciidoctor-maven-plugin diff --git a/linux-bash/json/src/main/bash/fruit.json b/linux-bash/json/src/main/bash/fruit.json new file mode 100644 index 0000000000..392d2290ae --- /dev/null +++ b/linux-bash/json/src/main/bash/fruit.json @@ -0,0 +1 @@ +{"fruit":{"name":"apple","color":"green","price":1.20}} diff --git a/linux-bash/json/src/main/bash/fruits.json b/linux-bash/json/src/main/bash/fruits.json new file mode 100644 index 0000000000..114a9a35cc --- /dev/null +++ b/linux-bash/json/src/main/bash/fruits.json @@ -0,0 +1,17 @@ +[ + { + "name": "apple", + "color": "green", + "price": 1.2 + }, + { + "name": "banana", + "color": "yellow", + "price": 0.5 + }, + { + "name": "kiwi", + "color": "green", + "price": 1.25 + } +] diff --git a/linux-bash/json/src/main/bash/jq.sh b/linux-bash/json/src/main/bash/jq.sh new file mode 100755 index 0000000000..786be304db --- /dev/null +++ b/linux-bash/json/src/main/bash/jq.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +#3.1. Beautify JSON +echo '{"fruit":{"name":"apple","color":"green","price":1.20}}' | jq '.' +jq '.' fruit.json +curl http://api.open-notify.org/iss-now.json | jq '.' + +#3.2. Accessing Properties +jq '.fruit' fruit.json +jq '.fruit.color' fruit.json +jq '.fruit.color,.fruit.price' fruit.json +echo '{ "with space": "hello" }' | jq '."with space"' + +#4.1. Iteration +echo '["x","y","z"]' | jq '.[]' +jq '.[] | .name' fruits.json +jq '.[].name' fruits.json + +#4.2. Accessing By Index +jq '.[1].price' fruits.json + +#4.3. Slicing +echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[6:9]' +echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[:6]' | jq '.[-2:]' + +#5.1. Getting Keys +jq '.fruit | keys' fruit.json + +#5.2. Returning the Length +jq '.fruit | length' fruit.json +jq '.fruit.name | length' fruit.json + +#5.3. Mapping Values +jq 'map(has("name"))' fruits.json +jq 'map(.price+2)' fruits.json + +#5.4. Min and Max +jq '[.[].price] | min' fruits.json +jq '[.[].price] | max' fruits.json + +#5.5. Selecting Values +jq '.[] | select(.price>0.5)' fruits.json +jq '.[] | select(.color=="yellow")' fruits.json +jq '.[] | select(.color=="yellow" and .price>=0.5)' fruits.json + +#5.6. Support For RegEx +jq '.[] | select(.name|test("^a.")) | .price' fruits.json + +#5.7. Find Unique Values +jq 'map(.color) | unique' fruits.json + +#5.8. Deleting Keys From JSON +jq 'del(.fruit.name)' fruit.json + +# 6. Transforming +jq '.query.pages | [.[] | map(.) | .[] | {page_title: .title, page_description: .extract}]' wikipedia.json diff --git a/linux-bash/json/src/main/bash/wikipedia.json b/linux-bash/json/src/main/bash/wikipedia.json new file mode 100644 index 0000000000..180b160bcc --- /dev/null +++ b/linux-bash/json/src/main/bash/wikipedia.json @@ -0,0 +1,22 @@ +{ + "query": { + "pages": [ + { + "21721040": { + "pageid": 21721040, + "ns": 0, + "title": "Stack Overflow", + "extract": "Some interesting text about Stack Overflow" + } + }, + { + "21721041": { + "pageid": 21721041, + "ns": 0, + "title": "Baeldung", + "extract": "A great place to learn about Java" + } + } + ] + } +} diff --git a/linux-bash/loops/README.md b/linux-bash/loops/README.md new file mode 100644 index 0000000000..8a0514f6f0 --- /dev/null +++ b/linux-bash/loops/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Linux Commands – Looping Through Directories](https://www.baeldung.com/linux/loop-directories) diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md new file mode 100644 index 0000000000..e0ee0c1600 --- /dev/null +++ b/linux-bash/text/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file) diff --git a/logging-modules/flogger/README.md b/logging-modules/flogger/README.md new file mode 100644 index 0000000000..ad7a25e24f --- /dev/null +++ b/logging-modules/flogger/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Flogger Fluent Logging](https://www.baeldung.com/flogger-logging) diff --git a/logging-modules/log4j2/README.md b/logging-modules/log4j2/README.md index dd326bc7a1..6a65ae9c02 100644 --- a/logging-modules/log4j2/README.md +++ b/logging-modules/log4j2/README.md @@ -5,3 +5,4 @@ - [Programmatic Configuration with Log4j 2](http://www.baeldung.com/log4j2-programmatic-config) - [Creating a Custom Log4j2 Appender](https://www.baeldung.com/log4j2-custom-appender) - [Get Log Output in JSON](http://www.baeldung.com/java-log-json-output) +- [System.out.println vs Loggers](https://www.baeldung.com/java-system-out-println-vs-loggers) diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java index 20366a229d..ae0eec727f 100644 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java @@ -1,33 +1,40 @@ package com.baeldung.logback; import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; +import java.util.List; + +import static java.util.stream.Collectors.toList; +import static org.hamcrest.Matchers.hasItems; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; public class MapAppenderIntegrationTest { - private Logger rootLogger; + private Logger logger; @Before - public void setUp() throws Exception { - rootLogger = (Logger) LoggerFactory.getLogger("ROOT"); + public void setUp() { + logger = (Logger) LoggerFactory.getLogger(MapAppenderIntegrationTest.class); } @Test - public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception { - rootLogger.info("Test from {}", this.getClass().getSimpleName()); - MapAppender appender = (MapAppender) rootLogger.getAppender("map"); - assertEquals(appender.getEventMap().size(), 1); + public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() { + logger.info("Test from {}", this.getClass().getSimpleName()); + MapAppender appender = (MapAppender) logger.getAppender("map"); + + List messages = appender.getEventMap().values().stream().map(ILoggingEvent::getMessage).collect(toList()); + assertThat(messages, hasItems("Test from {}")); } @Test - public void givenNoPrefixSet_whenLoggerEmitsEvent_thenAppenderReceivesNoEvent() throws Exception { - rootLogger.info("Test from {}", this.getClass().getSimpleName()); - MapAppender appender = (MapAppender) rootLogger.getAppender("badMap"); + public void givenNoPrefixSet_whenLoggerEmitsEvent_thenAppenderReceivesNoEvent() { + logger.info("Test from {}", this.getClass().getSimpleName()); + MapAppender appender = (MapAppender) logger.getAppender("badMap"); assertEquals(appender.getEventMap().size(), 0); } - } diff --git a/logging-modules/logback/src/test/resources/logback-test.xml b/logging-modules/logback/src/test/resources/logback-test.xml index df81f18cc2..89c0124738 100644 --- a/logging-modules/logback/src/test/resources/logback-test.xml +++ b/logging-modules/logback/src/test/resources/logback-test.xml @@ -28,4 +28,9 @@ + + + + + \ No newline at end of file diff --git a/lombok/pom.xml b/lombok/pom.xml index 2acf9e240d..b67320909e 100644 --- a/lombok/pom.xml +++ b/lombok/pom.xml @@ -76,7 +76,7 @@ - 1.18.4 + 1.18.10 1.0.0.Final diff --git a/lombok/src/main/java/com/baeldung/lombok/accessors/model/BasicAccount.java b/lombok/src/main/java/com/baeldung/lombok/accessors/model/BasicAccount.java new file mode 100644 index 0000000000..74ae51c040 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/accessors/model/BasicAccount.java @@ -0,0 +1,24 @@ +package com.baeldung.lombok.accessors.model; + +import java.math.BigDecimal; + +public class BasicAccount { + String name; + BigDecimal balance; + + public BigDecimal getBalance() { + return this.balance; + } + + public void setBalance(BigDecimal newBalance) { + this.balance = newBalance; + } + + public String getName() { + return this.name; + } + + public void setName(String accountName) { + this.name = accountName; + } +} diff --git a/lombok/src/main/java/com/baeldung/lombok/accessors/model/ChainedAccount.java b/lombok/src/main/java/com/baeldung/lombok/accessors/model/ChainedAccount.java new file mode 100644 index 0000000000..8fa9a2e8aa --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/accessors/model/ChainedAccount.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.accessors.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +import java.math.BigDecimal; + +@Accessors(chain = true) +@Getter +@Setter +public class ChainedAccount { + String name; + BigDecimal balance; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/accessors/model/ChainedFluentAccount.java b/lombok/src/main/java/com/baeldung/lombok/accessors/model/ChainedFluentAccount.java new file mode 100644 index 0000000000..22e85848bd --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/accessors/model/ChainedFluentAccount.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.accessors.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +import java.math.BigDecimal; + +@Accessors(fluent = true, chain = true) +@Getter +@Setter +public class ChainedFluentAccount { + String name; + BigDecimal balance; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/accessors/model/FluentAccount.java b/lombok/src/main/java/com/baeldung/lombok/accessors/model/FluentAccount.java new file mode 100644 index 0000000000..bc5e6ba70e --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/accessors/model/FluentAccount.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.accessors.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +import java.math.BigDecimal; + +@Accessors(fluent = true, chain = false) +@Getter +@Setter +public class FluentAccount { + String name; + BigDecimal balance; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/accessors/model/PrefixedAccount.java b/lombok/src/main/java/com/baeldung/lombok/accessors/model/PrefixedAccount.java new file mode 100644 index 0000000000..e3e3ae620b --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/accessors/model/PrefixedAccount.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.accessors.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +import java.math.BigDecimal; + + +@Accessors(prefix = {"s", "bd"}) +@Getter +@Setter +public class PrefixedAccount { + String sName; + BigDecimal bdBalance; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/accessors/model/PrefixedFluentAccount.java b/lombok/src/main/java/com/baeldung/lombok/accessors/model/PrefixedFluentAccount.java new file mode 100644 index 0000000000..462a9b41ec --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/accessors/model/PrefixedFluentAccount.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.accessors.model; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +import java.math.BigDecimal; + +@Accessors(prefix = {"s", "bd"}, fluent = true) +@Getter +@Setter +public class PrefixedFluentAccount { + String sName; + BigDecimal bdBalance; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/accessors/model/StandardAccount.java b/lombok/src/main/java/com/baeldung/lombok/accessors/model/StandardAccount.java new file mode 100644 index 0000000000..89727fef19 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/accessors/model/StandardAccount.java @@ -0,0 +1,13 @@ +package com.baeldung.lombok.accessors.model; + +import lombok.Getter; +import lombok.Setter; + +import java.math.BigDecimal; + +@Getter +@Setter +public class StandardAccount { + String name; + BigDecimal balance; +} diff --git a/lombok/src/test/java/com/baeldung/lombok/accessors/AccessorsUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/accessors/AccessorsUnitTest.java new file mode 100644 index 0000000000..679c7d39ef --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/accessors/AccessorsUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.lombok.accessors; + +import com.baeldung.lombok.accessors.model.*; +import org.junit.Test; + +import java.math.BigDecimal; + +import static org.junit.Assert.assertEquals; + +public class AccessorsUnitTest { + + @Test + public void givenBasicAccount_thenUseBasicAccessors() { + BasicAccount account = new BasicAccount(); + account.setBalance(BigDecimal.TEN); + account.setName("Basic Accessors"); + + assertEquals(BigDecimal.TEN, account.getBalance()); + assertEquals("Basic Accessors", account.getName()); + } + + @Test + public void givenFluentAccount_thenUseFluentAccessors() { + FluentAccount account = new FluentAccount(); + account.name("Fluent Account"); + account.balance(BigDecimal.TEN); + + assertEquals(BigDecimal.TEN, account.balance()); + assertEquals("Fluent Account", account.name()); + } + + @Test + public void givenChainedAccount_thenUseChainedAccessors() { + ChainedAccount account = new ChainedAccount(); + account.setName("Chained Account").setBalance(BigDecimal.TEN); + + assertEquals(BigDecimal.TEN, account.getBalance()); + assertEquals("Chained Account", account.getName()); + } + + @Test + public void givenChainedFluentAccount_thenUseChainedFluentAccessors() { + ChainedFluentAccount account = new ChainedFluentAccount() + .name("Fluent Account") + .balance(BigDecimal.TEN); + + assertEquals(BigDecimal.TEN, account.balance()); + assertEquals("Fluent Account", account.name()); + } + + @Test + public void givenPrefixedAccount_thenRemovePrefixFromAccessors() { + PrefixedAccount account = new PrefixedAccount(); + account.setName("Prefixed Fields"); + account.setBalance(BigDecimal.TEN); + + assertEquals(BigDecimal.TEN, account.getBalance()); + assertEquals("Prefixed Fields", account.getName()); + } + + @Test + public void givenPrefixedFluentAccount_thenRemovePrefixFromAccessors() { + PrefixedFluentAccount account = new PrefixedFluentAccount(); + account + .name("Prefixed Fluent Fields") + .balance(BigDecimal.TEN); + + assertEquals(BigDecimal.TEN, account.balance()); + assertEquals("Prefixed Fluent Fields", account.name()); + } + +} diff --git a/mapstruct/README.md b/mapstruct/README.md index be02c1186b..f5a1e1a092 100644 --- a/mapstruct/README.md +++ b/mapstruct/README.md @@ -5,4 +5,5 @@ This module contains articles about MapStruct. ###Relevant Articles: - [Quick Guide to MapStruct](https://www.baeldung.com/mapstruct) - [Custom Mapper with MapStruct](https://www.baeldung.com/mapstruct-custom-mapper) - +- [Using Multiple Source Objects with MapStruct](https://www.baeldung.com/mapstruct-multiple-source-objects) +- [Ignoring Unmapped Properties with MapStruct](https://www.baeldung.com/mapstruct-ignore-unmapped-properties) diff --git a/metrics/README.md b/metrics/README.md index b8a1bf026f..6050b2b310 100644 --- a/metrics/README.md +++ b/metrics/README.md @@ -8,4 +8,3 @@ This module contains articles about metrics. - [Introduction to Netflix Servo](https://www.baeldung.com/netflix-servo) - [Quick Guide to Micrometer](https://www.baeldung.com/micrometer) - [@Timed Annotation Using Metrics and AspectJ](https://www.baeldung.com/timed-metrics-aspectj) - diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 2a8d135483..02ac36218d 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -1,136 +1,142 @@ - 4.0.0 - com.baeldung.micronaut - micronaut - 0.1 - micronaut + 4.0.0 + com.baeldung.micronaut + micronaut + 0.1 + micronaut - - - - io.micronaut - bom - ${micronaut.version} - pom - import - - - - - - io.micronaut - http-client - compile - - - io.micronaut - http-server-netty - compile - - - io.micronaut - inject - compile - - - io.micronaut - runtime - compile - - - javax.annotation - javax.annotation-api - 1.3.2 - compile - - - io.micronaut - inject-java - provided - - - ch.qos.logback - logback-classic - 1.2.3 - runtime - - - junit - junit - 4.12 - test - - - io.projectreactor - reactor-core - 3.1.6.RELEASE - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.1.0 - - - package - - shade - - - - - ${exec.mainClass} - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - java - - -classpath - - ${exec.mainClass} - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - ${jdk.version} - ${jdk.version} - - -parameters - - - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.micronaut - inject-java + bom ${micronaut.version} - - - - - - - - - - com.baeldung.micronaut.helloworld.server.ServerApplication - 1.0.0.RC2 - 1.8 - + pom + import + + + + + + io.micronaut + http-client + compile + + + io.micronaut + http-server-netty + compile + + + io.micronaut + inject + compile + + + io.micronaut + runtime + compile + + + javax.annotation + javax.annotation-api + 1.3.2 + compile + + + io.micronaut + inject-java + provided + + + ch.qos.logback + logback-classic + 1.2.3 + runtime + + + junit + junit + 4.12 + test + + + io.projectreactor + reactor-core + 3.1.6.RELEASE + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + package + + shade + + + + + ${exec.mainClass} + + + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + java + + -classpath + + ${exec.mainClass} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + ${jdk.version} + ${jdk.version} + + -parameters + + + + io.micronaut + inject-java + ${micronaut.version} + + + + + + + + + + com.baeldung.micronaut.helloworld.server.ServerApplication + 1.0.0.RC2 + 1.8 + diff --git a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientUnitTest.java similarity index 95% rename from micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java rename to micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientUnitTest.java index c8c1d6b12a..336374d5a6 100644 --- a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java +++ b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientUnitTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class ConcreteGreetingClientTest +public class ConcreteGreetingClientUnitTest { private EmbeddedServer server; private ConcreteGreetingClient client; diff --git a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientUnitTest.java similarity index 94% rename from micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java rename to micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientUnitTest.java index 0f2ca460ac..c47fb3a31d 100644 --- a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java +++ b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientUnitTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class GreetingClientTest { +public class GreetingClientUnitTest { private EmbeddedServer server; private GreetingClient client; diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index edc115d186..fe272b56a3 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -78,6 +78,6 @@ 3.3.0 1.0.22.RELEASE - 2.1.7.RELEASE + 2.1.9.RELEASE diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index bda5fb70e7..84844dbb8b 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -1,6 +1,6 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 parent-kotlin parent-kotlin @@ -13,34 +13,34 @@ 1.0.0-SNAPSHOT - - - jcenter - http://jcenter.bintray.com - - - kotlin-ktor - https://dl.bintray.com/kotlin/ktor/ - - - kotlin-eap - http://dl.bintray.com/kotlin/kotlin-eap - - - spring-milestone - Spring Milestone Repository - http://repo.spring.io/milestone - - - - - - kotlin-eap - http://dl.bintray.com/kotlin/kotlin-eap - - - - + + + jcenter + http://jcenter.bintray.com + + + kotlin-ktor + https://dl.bintray.com/kotlin/ktor/ + + + kotlin-eap + http://dl.bintray.com/kotlin/kotlin-eap + + + spring-milestone + Spring Milestone Repository + http://repo.spring.io/milestone + + + + + + kotlin-eap + http://dl.bintray.com/kotlin/kotlin-eap + + + + org.springframework.boot @@ -56,15 +56,15 @@ org.jetbrains.kotlin kotlin-stdlib-jdk8 - - - org.jetbrains.kotlin - kotlin-stdlib - + + + org.jetbrains.kotlin + kotlin-stdlib + org.jetbrains.kotlin kotlin-reflect - + org.jetbrains.kotlinx @@ -113,9 +113,9 @@ ${project.basedir}/src/main/java ${java.version} - - -Xjvm-default=enable - + + -Xjvm-default=enable + diff --git a/patterns/design-patterns-creational/README.md b/patterns/design-patterns-creational/README.md index 99b9b39787..026115a6d6 100644 --- a/patterns/design-patterns-creational/README.md +++ b/patterns/design-patterns-creational/README.md @@ -6,4 +6,5 @@ - [Double-Checked Locking with Singleton](https://www.baeldung.com/java-singleton-double-checked-locking) - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [Automatic Generation of the Builder Pattern with FreeBuilder](https://www.baeldung.com/java-builder-pattern-freebuilder) -- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements) \ No newline at end of file +- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements) +- [Prototype Pattern in Java](https://www.baeldung.com/java-pattern-prototype) diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 3271f0c1b6..5bbdeecbea 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -8,3 +8,4 @@ This module contains articles about Object-relational Mapping (ORM) with Hiberna - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) - [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) - [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) +- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) diff --git a/persistence-modules/hibernate-parameters/pom.xml b/persistence-modules/hibernate-parameters/pom.xml deleted file mode 100644 index b744e181da..0000000000 --- a/persistence-modules/hibernate-parameters/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - com.baeldung - hibernate-parameters - 0.1-SNAPSHOT - hibernate-parameters - jar - Hibernate tutorial illustrating the use of named parameters - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - - - - org.hibernate - hibernate-core - 5.4.4.Final - - - - com.h2database - h2 - 1.4.196 - - - - - - - false - src/test/java - - **/*.xml - - - - src/test/resources - - - - - - true - - - diff --git a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.hbm.xml b/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.hbm.xml deleted file mode 100644 index 4055718776..0000000000 --- a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.hbm.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - diff --git a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.java b/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.java deleted file mode 100644 index f44b1bfd8a..0000000000 --- a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.hibernate_parameters; - -public class Event { - private Long id; - - private String title; - - public Event() { - } - - public Event(String title) { - this.title = title; - } - - public Long getId() { - return id; - } - - private void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } -} \ No newline at end of file diff --git a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/NamedParameterUnitTest.java b/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/NamedParameterUnitTest.java deleted file mode 100644 index 23854dc393..0000000000 --- a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/NamedParameterUnitTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.hibernate_parameters; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.query.Query; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - -public class NamedParameterUnitTest { - private SessionFactory sessionFactory; - - @Before - public void setUp() throws Exception { - final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() - .configure() - .build(); - try { - sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); - Session session = sessionFactory.openSession(); - session.beginTransaction(); - session.save(new Event("Event 1")); - session.save(new Event("Event 2")); - session.getTransaction().commit(); - session.close(); - } catch (Exception e) { - StandardServiceRegistryBuilder.destroy(registry); - } - } - - @After - public void tearDown() throws Exception { - if (sessionFactory != null) { - sessionFactory.close(); - } - } - - @Test - public void whenNamedParameterProvided_thenCorrect() { - Session session = sessionFactory.openSession(); - session.beginTransaction(); - Query query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class); - - // This binds the value "Event1" to the parameter :eventTitle - query.setParameter("eventTitle", "Event 1"); - - assertEquals(1, query.list().size()); - session.getTransaction().commit(); - session.close(); - } - - @Test(expected = org.hibernate.QueryException.class) - public void whenNamedParameterMissing_thenThrowsQueryException() { - Session session = sessionFactory.openSession(); - session.beginTransaction(); - Query query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class); - - try { - query.list(); - fail("We are expecting an exception!"); - } finally { - session.getTransaction().commit(); - session.close(); - } - } -} diff --git a/persistence-modules/hibernate-parameters/src/test/resources/hibernate.cfg.xml b/persistence-modules/hibernate-parameters/src/test/resources/hibernate.cfg.xml deleted file mode 100644 index 480baae4c1..0000000000 --- a/persistence-modules/hibernate-parameters/src/test/resources/hibernate.cfg.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - org.h2.Driver - jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE - sa - - - 1 - - org.hibernate.dialect.H2Dialect - - org.hibernate.cache.internal.NoCacheProvider - - true - - create - - - - - - \ No newline at end of file diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/fetchMode/Customer.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/fetchMode/Customer.java new file mode 100644 index 0000000000..5997602205 --- /dev/null +++ b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/fetchMode/Customer.java @@ -0,0 +1,39 @@ +package com.baeldung.fetchMode; + +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.HashSet; +import java.util.Set; + +@Entity +public class Customer { + + @Id + @GeneratedValue + private Long id; + + @OneToMany(mappedBy = "customer") + @Fetch(value = FetchMode.SELECT) + private Set orders = new HashSet<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Set getOrders() { + return orders; + } + + public void setOrders(Set orders) { + this.orders = orders; + } +} diff --git a/persistence-modules/hibernate5-2/src/main/java/com/baeldung/fetchMode/Order.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/fetchMode/Order.java new file mode 100644 index 0000000000..c031972830 --- /dev/null +++ b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/fetchMode/Order.java @@ -0,0 +1,50 @@ +package com.baeldung.fetchMode; + +import javax.persistence.*; + +@Entity +public class Order { + + @Id + @GeneratedValue + private Long id; + + private String name; + + @ManyToOne + @JoinColumn(name = "customer_id") + private Customer customer; + + public Order() { + + } + + public Order(String name, Customer customer) { + this.name = name; + this.customer = customer; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Customer getCustomer() { + return customer; + } + + public void setCustomer(Customer customer) { + this.customer = customer; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java index e64e836924..699890c457 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java @@ -26,7 +26,6 @@ public class CustomClassIntegrationTest { public void setUp() throws IOException { session = HibernateUtil.getSessionFactory().openSession(); transaction = session.beginTransaction(); - session.createNativeQuery("delete from manager").executeUpdate(); session.createNativeQuery("delete from department").executeUpdate(); Department department = new Department("Sales"); DeptEmployee employee = new DeptEmployee("John Smith", "001", department); diff --git a/persistence-modules/java-jpa-2/README.md b/persistence-modules/java-jpa-2/README.md index 1b4a175008..14433f8fc8 100644 --- a/persistence-modules/java-jpa-2/README.md +++ b/persistence-modules/java-jpa-2/README.md @@ -10,4 +10,6 @@ This module contains articles about the Java Persistence API (JPA) in Java. - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) - [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections) - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) -- More articles: [[<-- prev]](/java-jpa) \ No newline at end of file +- [JPA Annotation for the PostgreSQL TEXT Type](https://www.baeldung.com/jpa-annotation-postgresql-text-type) +- [Mapping a Single Entity to Multiple Tables in JPA](https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables) +- More articles: [[<-- prev]](/java-jpa) diff --git a/persistence-modules/jnosql/pom.xml b/persistence-modules/jnosql/pom.xml index 513a447b91..91ceddaadd 100644 --- a/persistence-modules/jnosql/pom.xml +++ b/persistence-modules/jnosql/pom.xml @@ -9,6 +9,13 @@ jnosql pom + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + jnosql-diana jnosql-artemis diff --git a/persistence-modules/sirix/README.md b/persistence-modules/sirix/README.md index 161e60c2cb..ab7fb65e44 100644 --- a/persistence-modules/sirix/README.md +++ b/persistence-modules/sirix/README.md @@ -2,4 +2,3 @@ - [Introduction to Sirix](https://www.baeldung.com/introduction-to-sirix) - [A Guide to SirixDB](https://www.baeldung.com/sirix) - diff --git a/persistence-modules/spring-boot-jdbi/README.md b/persistence-modules/spring-boot-jdbi/README.md new file mode 100644 index 0000000000..5d171fb2ca --- /dev/null +++ b/persistence-modules/spring-boot-jdbi/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Using JDBI with Spring Boot](https://www.baeldung.com/spring-boot-jdbi) diff --git a/persistence-modules/spring-boot-persistence-h2/pom.xml b/persistence-modules/spring-boot-persistence-h2/pom.xml index bd36a46144..30c727bfc8 100644 --- a/persistence-modules/spring-boot-persistence-h2/pom.xml +++ b/persistence-modules/spring-boot-persistence-h2/pom.xml @@ -26,11 +26,6 @@ com.h2database h2 - - org.springframework.boot - spring-boot-starter-test - test - diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index c7cda07a1a..3ad925f16b 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -17,14 +17,17 @@ org.springframework.boot spring-boot-starter-web + ${spring-boot.version} org.springframework.boot spring-boot-starter-thymeleaf + ${spring-boot.version} org.springframework.boot spring-boot-starter-data-jpa + ${spring-boot.version} com.zaxxer @@ -35,6 +38,7 @@ org.springframework.boot spring-boot-starter-test + ${spring-boot.version} org.mockito @@ -99,6 +103,7 @@ 2.0.1.Final 10.13.1.1 2.3.4 + 2.1.7.RELEASE diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java new file mode 100644 index 0000000000..26c2373cbe --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java @@ -0,0 +1,85 @@ +package com.baeldung.aggregation.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import java.util.Objects; + +@Entity +public class Comment { + @Id + private Integer id; + private Integer year; + private boolean approved; + private String content; + @ManyToOne + private Post post; + + public Comment() { + } + + public Comment(int id, int year, boolean approved, String content, Post post) { + this.id = id; + this.year = year; + this.approved = approved; + this.content = content; + this.post = post; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public boolean isApproved() { + return approved; + } + + public void setApproved(boolean approved) { + this.approved = approved; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public Post getPost() { + return post; + } + + public void setPost(Post post) { + this.post = post; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Comment)) { + return false; + } + Comment comment = (Comment) o; + return getId().equals(comment.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java new file mode 100644 index 0000000000..f396e080ae --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java @@ -0,0 +1,75 @@ +package com.baeldung.aggregation.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.List; +import java.util.Objects; + +@Entity +public class Post { + @Id + private Integer id; + private String title; + private String content; + @OneToMany(mappedBy = "post") + private List comments; + + public Post() { + } + + public Post(Integer id, String title, String content) { + this.id = id; + this.title = title; + this.content = content; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Post)) { + return false; + } + Post post = (Post) o; + return getId().equals(post.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java new file mode 100644 index 0000000000..510b52a47c --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java @@ -0,0 +1,27 @@ +package com.baeldung.aggregation.model.custom; + +public class CommentCount { + private Integer year; + private Long total; + + public CommentCount(Integer year, Long total) { + this.year = year; + this.total = total; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public Long getTotal() { + return total; + } + + public void setTotal(Long total) { + this.total = total; + } +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java new file mode 100644 index 0000000000..acb25cfd49 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java @@ -0,0 +1,8 @@ +package com.baeldung.aggregation.model.custom; + +public interface ICommentCount { + + Integer getYearComment(); + + Long getTotalComment(); +} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java new file mode 100644 index 0000000000..89e9345e94 --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.aggregation.repository; + +import com.baeldung.aggregation.model.Comment; +import com.baeldung.aggregation.model.custom.CommentCount; +import com.baeldung.aggregation.model.custom.ICommentCount; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface CommentRepository extends JpaRepository { + + @Query("SELECT c.year, COUNT(c.year) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") + List countTotalCommentsByYear(); + + @Query("SELECT new com.baeldung.aggregation.model.custom.CommentCount(c.year, COUNT(c.year)) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") + List countTotalCommentsByYearClass(); + + @Query("SELECT c.year AS yearComment, COUNT(c.year) AS totalComment FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") + List countTotalCommentsByYearInterface(); + + @Query(value = "SELECT c.year AS yearComment, COUNT(c.*) AS totalComment FROM comment AS c GROUP BY c.year ORDER BY c.year DESC", nativeQuery = true) + List countTotalCommentsByYearNative(); + +} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java new file mode 100644 index 0000000000..779ade7a3f --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java @@ -0,0 +1,107 @@ +package com.baeldung.aggregation; + +import com.baeldung.aggregation.model.custom.CommentCount; +import com.baeldung.aggregation.model.custom.ICommentCount; +import com.baeldung.aggregation.repository.CommentRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(SpringRunner.class) +@DataJpaTest + +@Sql(scripts = "/test-aggregation-data.sql") +public class SpringDataAggregateIntegrationTest { + + @Autowired + private CommentRepository commentRepository; + + @Test + public void whenQueryWithAggregation_thenReturnResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYear(); + + Object[] countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019[0], is(Integer.valueOf(2019))); + assertThat(countYear2019[1], is(1l)); + + Object[] countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018[0], is(Integer.valueOf(2018))); + assertThat(countYear2018[1], is(2l)); + + Object[] countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017[0], is(Integer.valueOf(2017))); + assertThat(countYear2017[1], is(1l)); + } + + @Test + public void whenQueryWithAggregation_thenReturnCustomResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYearClass(); + + CommentCount countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019.getYear(), is(Integer.valueOf(2019))); + assertThat(countYear2019.getTotal(), is(1l)); + + CommentCount countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018.getYear(), is(Integer.valueOf(2018))); + assertThat(countYear2018.getTotal(), is(2l)); + + CommentCount countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017.getYear(), is(Integer.valueOf(2017))); + assertThat(countYear2017.getTotal(), is(1l)); + } + + @Test + public void whenQueryWithAggregation_thenReturnInterfaceResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYearInterface(); + + ICommentCount countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); + assertThat(countYear2019.getTotalComment(), is(1l)); + + ICommentCount countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); + assertThat(countYear2018.getTotalComment(), is(2l)); + + ICommentCount countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); + assertThat(countYear2017.getTotalComment(), is(1l)); + } + + @Test + public void whenNativeQueryWithAggregation_thenReturnInterfaceResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYearNative(); + + ICommentCount countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); + assertThat(countYear2019.getTotalComment(), is(1l)); + + ICommentCount countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); + assertThat(countYear2018.getTotalComment(), is(2l)); + + ICommentCount countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); + assertThat(countYear2017.getTotalComment(), is(1l)); + } + +} diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql new file mode 100644 index 0000000000..12409a124e --- /dev/null +++ b/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql @@ -0,0 +1,7 @@ +INSERT INTO post (id, title, content) VALUES (1, 'Comment 1', 'Content 1'); +INSERT INTO post (id, title, content) VALUES (2, 'Comment 2', 'Content 2'); +INSERT INTO post (id, title, content) VALUES (3, 'Comment 3', 'Content 3'); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (1, 2019, false, 'Comment 1', 1); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (2, 2018, true, 'Comment 2', 1); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (3, 2018, true, 'Comment 3', 2); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (4, 2017, false, 'Comment 4', 3); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/pom.xml b/persistence-modules/spring-data-jpa-3/pom.xml index f743fce2a3..32f81d5745 100644 --- a/persistence-modules/spring-data-jpa-3/pom.xml +++ b/persistence-modules/spring-data-jpa-3/pom.xml @@ -18,29 +18,22 @@ + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot spring-boot-starter-data-jpa - org.postgresql - postgresql - ${postgresql.version} + com.h2database + h2 + runtime + ${h2.version} - - org.testcontainers - junit-jupiter - ${testcontainers.version} - test - - - org.testcontainers - postgresql - ${testcontainers.version} - test - org.springframework.boot spring-boot-starter-test @@ -71,8 +64,7 @@ - 1.12.2 - 42.2.8 + 1.4.200 diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/tx/Payment.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/Payment.java similarity index 97% rename from persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/tx/Payment.java rename to persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/Payment.java index 37f3d09381..2c24e5777e 100644 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/tx/Payment.java +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/Payment.java @@ -1,4 +1,4 @@ -package com.baeldung.tx; +package com.baeldung.model; import javax.persistence.*; diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/User.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/User.java new file mode 100644 index 0000000000..94d0c023f2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/User.java @@ -0,0 +1,42 @@ +package com.baeldung.model; + +import javax.persistence.*; +import java.util.Set; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Long id; + + private String username; + + @ElementCollection + private Set permissions; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Set getPermissions() { + return permissions; + } + + public void setPermissions(Set permissions) { + this.permissions = permissions; + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java new file mode 100644 index 0000000000..bb3ce781f6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.repository; + +import com.baeldung.model.User; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + + @EntityGraph(attributePaths = "permissions") + Optional findDetailedByUsername(String username); + + Optional findSummaryByUsername(String username); + + Optional findByUsername(String username); +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/SimpleUserService.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/SimpleUserService.java new file mode 100644 index 0000000000..6782254f61 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/SimpleUserService.java @@ -0,0 +1,24 @@ +package com.baeldung.service; + +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Service +public class SimpleUserService implements UserService { + + private final UserRepository userRepository; + + public SimpleUserService(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + @Transactional(readOnly = true) + public Optional findOne(String username) { + return userRepository.findDetailedByUsername(username); + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/UserService.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/UserService.java new file mode 100644 index 0000000000..11b3dc82ce --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/UserService.java @@ -0,0 +1,9 @@ +package com.baeldung.service; + +import com.baeldung.model.User; + +import java.util.Optional; + +public interface UserService { + Optional findOne(String username); +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/DetailedUserDto.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/DetailedUserDto.java new file mode 100644 index 0000000000..0d8fe02b91 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/DetailedUserDto.java @@ -0,0 +1,45 @@ +package com.baeldung.web; + +import com.baeldung.model.User; + +import java.util.Set; + +public class DetailedUserDto { + + private Long id; + private String username; + private Set permissions; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Set getPermissions() { + return permissions; + } + + public void setPermissions(Set permissions) { + this.permissions = permissions; + } + + public static DetailedUserDto fromEntity(User user) { + DetailedUserDto detailed = new DetailedUserDto(); + detailed.setId(user.getId()); + detailed.setUsername(user.getUsername()); + detailed.setPermissions(user.getPermissions()); + + return detailed; + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/UserController.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/UserController.java new file mode 100644 index 0000000000..867d60cc2f --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/UserController.java @@ -0,0 +1,27 @@ +package com.baeldung.web; + +import com.baeldung.service.UserService; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/users") +public class UserController { + + private final UserService userService; + + public UserController(UserService userService) { + this.userService = userService; + } + + @GetMapping("/{username}") + public ResponseEntity findOne(@PathVariable String username) { + return userService.findOne(username) + .map(DetailedUserDto::fromEntity) + .map(ResponseEntity::ok) + .orElse(ResponseEntity.notFound().build()); + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java new file mode 100644 index 0000000000..ba94fc111b --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java @@ -0,0 +1,54 @@ +package com.baeldung.osiv; + +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Arrays; +import java.util.HashSet; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class UserControllerIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private MockMvc mockMvc; + + @BeforeEach + void setUp() { + User user = new User(); + user.setUsername("root"); + user.setPermissions(new HashSet<>(Arrays.asList("PERM_READ", "PERM_WRITE"))); + + userRepository.save(user); + } + + @Test + void givenTheUserExists_WhenOsivIsEnabled_ThenLazyInitWorkEverywhere() throws Exception { + mockMvc.perform(get("/users/root")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value("root")) + .andExpect(jsonPath("$.permissions", containsInAnyOrder("PERM_READ", "PERM_WRITE"))); + } + + @AfterEach + void flushDb() { + userRepository.deleteAll(); + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java index 62d64d4372..1ce8e91ec5 100644 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java @@ -1,10 +1,10 @@ package com.baeldung.tx; +import com.baeldung.model.Payment; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.transaction.PlatformTransactionManager; @@ -14,27 +14,17 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; -import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; import javax.persistence.EntityManager; -import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace.NONE; import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; @DataJpaTest -@Testcontainers @ActiveProfiles("test") -@AutoConfigureTestDatabase(replace = NONE) @Transactional(propagation = NOT_SUPPORTED) class ManualTransactionIntegrationTest { - @Container - private static PostgreSQLContainer pg = initPostgres(); - @Autowired private PlatformTransactionManager transactionManager; @@ -159,13 +149,4 @@ class ManualTransactionIntegrationTest { .getResultList()).hasSize(1); } - private static PostgreSQLContainer initPostgres() { - PostgreSQLContainer pg = new PostgreSQLContainer<>("postgres:11.1") - .withDatabaseName("baeldung") - .withUsername("test") - .withPassword("test"); - pg.setPortBindings(singletonList("54320:5432")); - - return pg; - } } diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties index aa7093f751..f9497c8f37 100644 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties +++ b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties @@ -1,4 +1,2 @@ spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:postgresql://localhost:54320/baeldung -spring.datasource.username=test -spring.datasource.password=test +spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 4ae8ac0a87..cd8c729844 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -87,7 +87,8 @@ ${maven-surefire-plugin.version} true - true + false + 0 -Xmx1024m diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java index 1333f94653..af790c99b7 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java @@ -38,7 +38,7 @@ public class RedisKeyCommandsIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java index 88c4fa6eed..58846d7c27 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java @@ -36,7 +36,7 @@ public class RedisTemplateListOpsIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java index afa5267582..5d12f90f34 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java @@ -38,7 +38,7 @@ public class RedisTemplateValueOpsIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 1c69b63c09..6f9e6a8757 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -33,7 +33,7 @@ public class RedisMessageListenerIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } @@ -46,7 +46,7 @@ public class RedisMessageListenerIntegrationTest { public void testOnMessage() throws Exception { String message = "Message " + UUID.randomUUID(); redisMessagePublisher.publish(message); - Thread.sleep(100); + Thread.sleep(1000); assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message)); } } \ No newline at end of file diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index b1a36475c3..24191a42b9 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -34,7 +34,7 @@ public class StudentRepositoryIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java index e093892365..f5c8177cbe 100644 --- a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,16 +1,35 @@ package org.baeldung; +import com.baeldung.spring.data.redis.config.RedisConfig; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import redis.embedded.RedisServerBuilder; -import com.baeldung.spring.data.redis.config.RedisConfig; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; @RunWith(SpringJUnit4ClassRunner.class) +@DirtiesContext(classMode = BEFORE_CLASS) @ContextConfiguration(classes = RedisConfig.class) public class SpringContextIntegrationTest { + private static redis.embedded.RedisServer redisServer; + + @BeforeClass + public static void startRedisServer() { + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() { + redisServer.stop(); + } + @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index d04e9f6f41..489d990fc3 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -13,6 +13,7 @@ - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) +- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource/) ### Eclipse Config diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index 8e55a59c7c..db0d0ce83c 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -12,6 +12,7 @@ - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) - [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) +- [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/pom.xml b/pom.xml index 5404c908d3..6f980a893a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,3 @@ - @@ -381,7 +380,7 @@ cloud-foundry-uaa/cf-uaa-oauth2-client cloud-foundry-uaa/cf-uaa-oauth2-resource-server code-generation - core-groovy + core-groovy core-groovy-2 core-groovy-collections @@ -391,13 +390,22 @@ core-java-modules/core-java-8-2 core-java-modules/core-java-annotations core-java-modules/core-java-streams + core-java-modules/core-java-streams-2 + core-java-modules/core-java-streams-3 + core-java-modules/core-java-function core-java-modules/core-java-lang-math - - + + core-java-modules/core-java-text core-java-modules/core-java-lambdas - + core-java-modules/core-java-arrays core-java-modules/core-java-arrays-2 @@ -415,6 +423,7 @@ core-java-modules/core-java-io core-java-modules/core-java-io-files core-java-modules/core-java-nio + core-java-modules/core-java-nio-2 core-java-modules/core-java-security core-java-modules/core-java-exceptions core-java-modules/core-java-lang-syntax @@ -431,7 +440,12 @@ core-java-modules/core-java-sun core-java-modules/core-java-string-conversions core-java-modules/core-java-string-conversions-2 + core-java-modules/core-java-string-operations + core-java-modules/core-java-string-operations-2 + core-java-modules/core-java-string-algorithms + core-java-modules/core-java-string-algorithms-2 core-java-modules/core-java-string-apis + core-java-modules/core-java-strings core-java-modules/core-java core-java-modules/core-java-jvm core-scala @@ -482,6 +496,7 @@ jackson-2 jackson-simple java-collections-conversions + java-collections-conversions-2 java-collections-maps java-collections-maps-2 java-jdi @@ -493,12 +508,6 @@ java-numbers-2 java-rmi java-spi - java-streams - - java-strings - java-strings-2 - java-strings-3 - java-strings-ops java-vavr-stream java-websocket javafx @@ -532,6 +541,7 @@ libraries libraries-2 + libraries-3 libraries-data libraries-data-2 libraries-data-db @@ -592,8 +602,10 @@ rule-engines rsocket - rxjava - rxjava-2 + rxjava-core + rxjava-observables + rxjava-operators + rxjava-libraries software-security/sql-injection-samples tensorflow-java @@ -609,7 +621,7 @@ spring-boot-nashorn java-blockchain -wildfly + wildfly @@ -710,10 +722,11 @@ spring-boot-parent spring-boot-property-exp spring-boot-security + spring-boot-springdoc spring-boot-testing spring-boot-vue spring-caching - spring-boot-libraries + spring-boot-libraries spring-cloud @@ -910,6 +923,7 @@ spring-boot-keycloak spring-boot-mvc spring-boot-property-exp + spring-boot-springdoc spring-boot-vue spring-cloud spring-cloud/spring-cloud-archaius/basic-config @@ -1145,7 +1159,7 @@ cloud-foundry-uaa/cf-uaa-oauth2-client cloud-foundry-uaa/cf-uaa-oauth2-resource-server code-generation - core-groovy + core-groovy core-groovy-2 core-groovy-collections @@ -1154,12 +1168,21 @@ core-java-modules/core-java-8-2 core-java-modules/core-java-annotations core-java-modules/core-java-streams + core-java-modules/core-java-streams-2 + core-java-modules/core-java-streams-3 + core-java-modules/core-java-function core-java-modules/core-java-lang-math - - + + core-java-modules/core-java-text - + core-java-modules/core-java-arrays core-java-modules/core-java-arrays-2 @@ -1177,6 +1200,7 @@ core-java-modules/core-java-io core-java-modules/core-java-io-files core-java-modules/core-java-nio + core-java-modules/core-java-nio-2 core-java-modules/core-java-security core-java-modules/core-java-exceptions core-java-modules/core-java-lang-syntax @@ -1191,9 +1215,14 @@ core-java-modules/core-java-perf core-java-modules/core-java-sun core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-apis - core-scala + core-java-modules/core-java-string-conversions-2 + core-java-modules/core-java-string-operations + core-java-modules/core-java-string-operations-2 + core-java-modules/core-java-string-algorithms + core-java-modules/core-java-string-algorithms-2 + core-java-modules/core-java-string-apis + core-java-modules/core-java-strings + core-scala couchbase custom-pmd @@ -1241,6 +1270,7 @@ jackson-2 jackson-simple java-collections-conversions + java-collections-conversions-2 java-collections-maps java-collections-maps-2 java-jdi @@ -1252,12 +1282,6 @@ java-numbers-2 java-rmi java-spi - java-streams - - java-strings - java-strings-2 - java-strings-3 - java-strings-ops java-vavr-stream java-websocket javafx @@ -1289,6 +1313,7 @@ libraries + libraries-3 libraries-data libraries-data-2 libraries-data-db @@ -1347,8 +1372,10 @@ rule-engines rsocket - rxjava - rxjava-2 + rxjava-core + rxjava-observables + rxjava-operators + rxjava-libraries oauth2-framework-impl spf4j spring-boot-performance @@ -1443,8 +1470,9 @@ spring-boot-parent spring-boot-property-exp spring-boot-security + spring-boot-springdoc spring-boot-vue - spring-caching + spring-caching spring-cloud spring-cloud-bus diff --git a/quarkus/pom.xml b/quarkus/pom.xml index 5190d0932a..31e3c8f8a0 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -1,115 +1,121 @@ - 4.0.0 - com.baeldung.quarkus - quarkus - 1.0-SNAPSHOT - quarkus - - - 2.22.0 - 0.15.0 - 1.8 - UTF-8 - 1.8 - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + 4.0.0 + com.baeldung.quarkus + quarkus + 1.0-SNAPSHOT + quarkus + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 2.22.0 + 0.15.0 + 1.8 + UTF-8 + 1.8 + + + + + io.quarkus + quarkus-bom + ${quarkus.version} + pom + import + + + - - io.quarkus - quarkus-bom - ${quarkus.version} - pom - import - - - - - - io.quarkus - quarkus-resteasy - - - io.quarkus - quarkus-junit5 - test - - - io.rest-assured - rest-assured - test - - - - - - io.quarkus - quarkus-maven-plugin - ${quarkus.version} - - - - build - - - - - - maven-surefire-plugin - ${surefire-plugin.version} - - - org.jboss.logmanager.LogManager - - - - - - - - native - - - native - - - - - + io.quarkus - quarkus-maven-plugin - ${quarkus.version} - - - - native-image - + quarkus-resteasy + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + io.quarkus + quarkus-maven-plugin + ${quarkus.version} + + + + build + + + + + + maven-surefire-plugin + ${surefire-plugin.version} - true + + org.jboss.logmanager.LogManager + - - - - - maven-failsafe-plugin - ${surefire-plugin.version} - - - - integration-test - verify - - - - ${project.build.directory}/${project.build.finalName}-runner - - - - - + - - - + + + + native + + + native + + + + + + io.quarkus + quarkus-maven-plugin + ${quarkus.version} + + + + native-image + + + true + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + + + + + + + + + diff --git a/rxjava-2/README.md b/rxjava-2/README.md deleted file mode 100644 index 87f606a323..0000000000 --- a/rxjava-2/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## RxJava - -This module contains articles about RxJava. - -### Relevant articles: - -- [RxJava and Error Handling](https://www.baeldung.com/rxjava-error-handling) -- [RxJava 2 – Flowable](https://www.baeldung.com/rxjava-2-flowable) -- [RxJava Maybe](https://www.baeldung.com/rxjava-maybe) -- [Introduction to RxRelay for RxJava](https://www.baeldung.com/rx-relay) -- [Combining RxJava Completables](https://www.baeldung.com/rxjava-completable) -- [Converting Synchronous and Asynchronous APIs to Observables using RxJava2](https://www.baeldung.com/rxjava-apis-to-observables) -- [RxJava Hooks](https://www.baeldung.com/rxjava-hooks) -- More articles: [[<-- prev]](/rxjava) diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml deleted file mode 100644 index 47d16ec8dd..0000000000 --- a/rxjava-2/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - rxjava-2 - rxjava-2 - 1.0-SNAPSHOT - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - io.reactivex.rxjava2 - rxjava - ${rx.java2.version} - - - com.jayway.awaitility - awaitility - ${awaitility.version} - - - org.assertj - assertj-core - ${assertj.version} - - - com.jakewharton.rxrelay2 - rxrelay - ${rxrelay.version} - - - - com.github.akarnokd - rxjava2-extensions - ${rxjava2.ext.version} - - - - - 3.8.0 - 2.2.2 - 1.7.0 - 2.0.0 - 0.20.4 - - \ No newline at end of file diff --git a/rxjava-2/src/main/resources/logback.xml b/rxjava-2/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/rxjava-2/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/rxjava-core/README.md b/rxjava-core/README.md new file mode 100644 index 0000000000..2773bd9423 --- /dev/null +++ b/rxjava-core/README.md @@ -0,0 +1,16 @@ +## RxJava + +This module contains articles about RxJava. + +### Relevant articles: + +- [Dealing with Backpressure with RxJava](https://www.baeldung.com/rxjava-backpressure) +- [How to Test RxJava?](https://www.baeldung.com/rxjava-testing) +- [Introduction to RxJava](https://www.baeldung.com/rx-java) +- [Schedulers in RxJava](https://www.baeldung.com/rxjava-schedulers) +- [Difference Between Flatmap and Switchmap in RxJava](https://www.baeldung.com/rxjava-flatmap-switchmap) +- [RxJava and Error Handling](https://www.baeldung.com/rxjava-error-handling) +- [RxJava Maybe](https://www.baeldung.com/rxjava-maybe) +- [Combining RxJava Completables](https://www.baeldung.com/rxjava-completable) +- [RxJava Hooks](https://www.baeldung.com/rxjava-hooks) +- More articles: [[next -->]](/rxjava-2) diff --git a/rxjava-core/pom.xml b/rxjava-core/pom.xml new file mode 100644 index 0000000000..401ad83808 --- /dev/null +++ b/rxjava-core/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + rxjava-core + 1.0-SNAPSHOT + rxjava-core + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex + rxjava + ${rx.java.version} + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + + org.assertj + assertj-core + ${assertj.version} + + + + + 3.8.0 + 1.2.5 + 1.7.0 + 2.2.2 + + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ComputeFunction.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ComputeFunction.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ComputeFunction.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ComputeFunction.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ObservableImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ObservableImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ObservableImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ObservableImpl.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ResourceManagement.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ResourceManagement.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ResourceManagement.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ResourceManagement.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/SingleImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/SingleImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/SingleImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/SingleImpl.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/SubjectImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/SubjectImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/SubjectImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/SubjectImpl.java diff --git a/java-strings-ops/src/main/resources/logback.xml b/rxjava-core/src/main/resources/logback.xml similarity index 100% rename from java-strings-ops/src/main/resources/logback.xml rename to rxjava-core/src/main/resources/logback.xml diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java similarity index 96% rename from rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java index b79fa9af22..f71d9e8839 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java +++ b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java @@ -1,84 +1,84 @@ -package com.baeldung.rxjava; - -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Test; - -import io.reactivex.Observable; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; - -public class RxJavaHooksManualTest { - - private boolean initHookCalled = false; - private boolean hookCalled = false; - - @Test - public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.io()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @Test - public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { - - RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 15) - .map(v -> v * 2) - .subscribeOn(Schedulers.newThread()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @Test - public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.single()) - .test(); - assertTrue(hookCalled && initHookCalled); - - } - - @After - public void reset() { - hookCalled = false; - initHookCalled = false; - RxJavaPlugins.reset(); - } -} +package com.baeldung.rxjava; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import io.reactivex.Observable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksManualTest { + + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.io()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { + + RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 15) + .map(v -> v * 2) + .subscribeOn(Schedulers.newThread()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + assertTrue(hookCalled && initHookCalled); + + } + + @After + public void reset() { + hookCalled = false; + initHookCalled = false; + RxJavaPlugins.reset(); + } +} diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java similarity index 96% rename from rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java index dd4287a4a9..cea6cc70f6 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java +++ b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java @@ -1,244 +1,244 @@ -package com.baeldung.rxjava; - -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Test; - -import io.reactivex.Completable; -import io.reactivex.Flowable; -import io.reactivex.Maybe; -import io.reactivex.Observable; -import io.reactivex.Single; -import io.reactivex.flowables.ConnectableFlowable; -import io.reactivex.observables.ConnectableObservable; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; - -public class RxJavaHooksUnitTest { - - private boolean initHookCalled = false; - private boolean hookCalled = false; - - @Test - public void givenObservable_whenError_shouldExecuteTheHook() { - RxJavaPlugins.setErrorHandler(throwable -> { - hookCalled = true; - }); - - Observable.error(new IllegalStateException()) - .subscribe(); - assertTrue(hookCalled); - } - - @Test - public void givenCompletable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnCompletableAssembly(completable -> { - hookCalled = true; - return completable; - }); - Completable.fromSingle(Single.just(1)); - assertTrue(hookCalled); - } - - @Test - public void givenCompletable_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { - hookCalled = true; - return observer; - }); - - Completable.fromSingle(Single.just(1)) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenObservable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnObservableAssembly(observable -> { - hookCalled = true; - return observable; - }); - - Observable.range(1, 10); - assertTrue(hookCalled); - } - - @Test - public void givenObservable_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { - hookCalled = true; - return observer; - }); - - Observable.range(1, 10) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenConnectableObservable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { - hookCalled = true; - return connectableObservable; - }); - - ConnectableObservable.range(1, 10) - .publish() - .connect(); - assertTrue(hookCalled); - } - - @Test - public void givenFlowable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnFlowableAssembly(flowable -> { - hookCalled = true; - return flowable; - }); - - Flowable.range(1, 10); - assertTrue(hookCalled); - } - - @Test - public void givenFlowable_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { - hookCalled = true; - return observer; - }); - - Flowable.range(1, 10) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { - hookCalled = true; - return connectableFlowable; - }); - - ConnectableFlowable.range(1, 10) - .publish() - .connect(); - assertTrue(hookCalled); - } - - @Test - public void givenParallel_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { - hookCalled = true; - return parallelFlowable; - }); - - Flowable.range(1, 10) - .parallel(); - assertTrue(hookCalled); - } - - @Test - public void givenMaybe_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnMaybeAssembly(maybe -> { - hookCalled = true; - return maybe; - }); - - Maybe.just(1); - assertTrue(hookCalled); - } - - @Test - public void givenMaybe_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { - hookCalled = true; - return observer; - }); - - Maybe.just(1) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenSingle_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnSingleAssembly(single -> { - hookCalled = true; - return single; - }); - - Single.just(1); - assertTrue(hookCalled); - } - - @Test - public void givenSingle_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { - hookCalled = true; - return observer; - }); - - Single.just(1) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() { - - RxJavaPlugins.setScheduleHandler((runnable) -> { - hookCalled = true; - return runnable; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.single()) - .test(); - hookCalled = false; - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.computation()) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenComputationScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.computation()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @After - public void reset() { - initHookCalled = false; - hookCalled = false; - RxJavaPlugins.reset(); - } -} +package com.baeldung.rxjava; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Maybe; +import io.reactivex.Observable; +import io.reactivex.Single; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.observables.ConnectableObservable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksUnitTest { + + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenObservable_whenError_shouldExecuteTheHook() { + RxJavaPlugins.setErrorHandler(throwable -> { + hookCalled = true; + }); + + Observable.error(new IllegalStateException()) + .subscribe(); + assertTrue(hookCalled); + } + + @Test + public void givenCompletable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnCompletableAssembly(completable -> { + hookCalled = true; + return completable; + }); + Completable.fromSingle(Single.just(1)); + assertTrue(hookCalled); + } + + @Test + public void givenCompletable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { + hookCalled = true; + return observer; + }); + + Completable.fromSingle(Single.just(1)) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenObservable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnObservableAssembly(observable -> { + hookCalled = true; + return observable; + }); + + Observable.range(1, 10); + assertTrue(hookCalled); + } + + @Test + public void givenObservable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { + hookCalled = true; + return observer; + }); + + Observable.range(1, 10) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenConnectableObservable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { + hookCalled = true; + return connectableObservable; + }); + + ConnectableObservable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); + } + + @Test + public void givenFlowable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnFlowableAssembly(flowable -> { + hookCalled = true; + return flowable; + }); + + Flowable.range(1, 10); + assertTrue(hookCalled); + } + + @Test + public void givenFlowable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { + hookCalled = true; + return observer; + }); + + Flowable.range(1, 10) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { + hookCalled = true; + return connectableFlowable; + }); + + ConnectableFlowable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); + } + + @Test + public void givenParallel_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { + hookCalled = true; + return parallelFlowable; + }); + + Flowable.range(1, 10) + .parallel(); + assertTrue(hookCalled); + } + + @Test + public void givenMaybe_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnMaybeAssembly(maybe -> { + hookCalled = true; + return maybe; + }); + + Maybe.just(1); + assertTrue(hookCalled); + } + + @Test + public void givenMaybe_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { + hookCalled = true; + return observer; + }); + + Maybe.just(1) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenSingle_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnSingleAssembly(single -> { + hookCalled = true; + return single; + }); + + Single.just(1); + assertTrue(hookCalled); + } + + @Test + public void givenSingle_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { + hookCalled = true; + return observer; + }); + + Single.just(1) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() { + + RxJavaPlugins.setScheduleHandler((runnable) -> { + hookCalled = true; + return runnable; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + hookCalled = false; + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenComputationScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @After + public void reset() { + initHookCalled = false; + hookCalled = false; + RxJavaPlugins.reset(); + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/SingleUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/SingleUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java diff --git a/rxjava-libraries/README.md b/rxjava-libraries/README.md new file mode 100644 index 0000000000..ac8aac6908 --- /dev/null +++ b/rxjava-libraries/README.md @@ -0,0 +1,10 @@ +## RxJava Libraries + + This module contains articles about RxJava libraries + +### Related Articles: + +- [RxJava 2 – Flowable](https://www.baeldung.com/rxjava-2-flowable) +- [Introduction to RxRelay for RxJava](https://www.baeldung.com/rx-relay) +- [Introduction to rxjava-jdbc](https://www.baeldung.com/rxjava-jdbc) + diff --git a/rxjava-libraries/pom.xml b/rxjava-libraries/pom.xml new file mode 100644 index 0000000000..541d9116c8 --- /dev/null +++ b/rxjava-libraries/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + rxjava-libraries + 1.0-SNAPSHOT + rxjava-libraries + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex + rxjava + ${rx.java.version} + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jakewharton.rxrelay2 + rxrelay + ${rxrelay.version} + + + com.github.davidmoten + rxjava-jdbc + ${rx.java.jdbc.version} + + + com.h2database + h2 + ${h2.version} + runtime + + + org.assertj + assertj-core + ${assertj.version} + + + + + + 0.7.11 + 1.2.5 + 2.0.0 + 2.2.2 + 3.8.0 + + + \ No newline at end of file diff --git a/rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/RandomRelay.java similarity index 100% rename from rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/RandomRelay.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Connector.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Connector.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Connector.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Connector.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Employee.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Employee.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Employee.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Employee.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Manager.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Manager.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Manager.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Manager.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Utils.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Utils.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Utils.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Utils.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java diff --git a/rxjava/src/test/resources/actual_clob b/rxjava-libraries/src/test/resources/actual_clob similarity index 100% rename from rxjava/src/test/resources/actual_clob rename to rxjava-libraries/src/test/resources/actual_clob diff --git a/rxjava/src/test/resources/expected_clob b/rxjava-libraries/src/test/resources/expected_clob similarity index 100% rename from rxjava/src/test/resources/expected_clob rename to rxjava-libraries/src/test/resources/expected_clob diff --git a/rxjava-observables/README.md b/rxjava-observables/README.md new file mode 100644 index 0000000000..3bec990012 --- /dev/null +++ b/rxjava-observables/README.md @@ -0,0 +1,11 @@ +## RxJava Observables + + This module contains articles about RxJava Observables + +### Related Articles: + +- [Combining Observables in RxJava](https://www.baeldung.com/rxjava-combine-observables) +- [RxJava One Observable, Multiple Subscribers](https://www.baeldung.com/rxjava-multiple-subscribers-observable) +- [RxJava StringObservable](https://www.baeldung.com/rxjava-string) +- [Filtering Observables in RxJava](https://www.baeldung.com/rxjava-filtering) + diff --git a/rxjava-observables/pom.xml b/rxjava-observables/pom.xml new file mode 100644 index 0000000000..c2bf0bcd88 --- /dev/null +++ b/rxjava-observables/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + rxjava-observables + 1.0-SNAPSHOT + rxjava-observables + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex + rxjava + ${rx.java.version} + + + io.reactivex + rxjava-string + ${rx.java.string.version} + + + org.assertj + assertj-core + ${assertj.version} + + + + + + 1.1.1 + 1.2.5 + 3.8.0 + + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java b/rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java rename to rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java b/rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java rename to rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java diff --git a/rxjava-operators/README.md b/rxjava-operators/README.md new file mode 100644 index 0000000000..293d310bbd --- /dev/null +++ b/rxjava-operators/README.md @@ -0,0 +1,12 @@ +## RxJava Operators + + This module contains articles about RxJava Operators + +### Related Articles: + +- [Mathematical and Aggregate Operators in RxJava](https://www.baeldung.com/rxjava-math) +- [Observable Utility Operators in RxJava](https://www.baeldung.com/rxjava-observable-operators) +- [Implementing Custom Operators in RxJava](https://www.baeldung.com/rxjava-custom-operators) +- [Converting Synchronous and Asynchronous APIs to Observables using RxJava2](https://www.baeldung.com/rxjava-apis-to-observables) + + diff --git a/rxjava/pom.xml b/rxjava-operators/pom.xml similarity index 66% rename from rxjava/pom.xml rename to rxjava-operators/pom.xml index 85106d1127..8064613f45 100644 --- a/rxjava/pom.xml +++ b/rxjava-operators/pom.xml @@ -1,11 +1,11 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - rxjava + rxjava-operators 1.0-SNAPSHOT - rxjava - + rxjava-operators + com.baeldung parent-java @@ -19,48 +19,40 @@ rxjava ${rx.java.version} - - io.reactivex - rxjava-math - ${rx.java.math.version} + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} - + - io.reactivex - rxjava-string - ${rx.java.string.version} - - - - com.jayway.awaitility - awaitility - ${awaitility.version} - - - com.github.davidmoten - rxjava-jdbc - ${rx.java.jdbc.version} - - - com.h2database - h2 - ${h2.version} - runtime + com.github.akarnokd + rxjava2-extensions + ${rxjava2.ext.version} org.assertj assertj-core ${assertj.version} + + io.reactivex + rxjava-math + ${rx.java.math.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + 0.20.4 + 2.2.2 3.8.0 1.2.5 - 0.7.11 1.0.0 - 1.1.1 1.7.0 diff --git a/rxjava/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java b/rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java rename to rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/operator/ToLength.java b/rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToLength.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/operator/ToLength.java rename to rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToLength.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java similarity index 96% rename from rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java index 90f4fe94ae..2842fab80e 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java +++ b/rxjava-operators/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java @@ -1,107 +1,107 @@ -package com.baeldung.rxjava; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.junit.Test; - -import hu.akarnokd.rxjava2.async.AsyncObservable; -import io.reactivex.Observable; - -public class AsyncAndSyncToObservableIntegrationTest { - - AtomicInteger counter = new AtomicInteger(); - Callable callable = () -> counter.incrementAndGet(); - - /* Method will execute every time it gets subscribed*/ - @Test - public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() { - - Observable source = Observable.fromCallable(callable); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(i); - - assertEquals(i, counter.get()); - } - } - - /* Method will execute only once and cache its result.*/ - @Test - public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() { - - Observable source = AsyncObservable.start(callable); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(1); - - assertEquals(1, counter.get()); - } - } - - /* Method will execute only once and cache its result.*/ - @Test - public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { - - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future future = executor.submit(callable); - Observable source = Observable.fromFuture(future); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(1); - - assertEquals(1, counter.get()); - } - - executor.shutdown(); - } - - /* Method will execute every time it gets subscribed*/ - @Test - public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() { - - ExecutorService executor = Executors.newSingleThreadExecutor(); - Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(i); - - assertEquals(i, counter.get()); - } - - executor.shutdown(); - } - - /*Method will execute only once and cache its result.*/ - @Test - public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { - List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); - ExecutorService exec = Executors.newSingleThreadExecutor(); - Callable> callable = () -> Observable.fromIterable(list); - Observable source = AsyncObservable.deferFuture(() -> exec.submit(callable)); - for (int i = 1; i < 4; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(1, 2, 3); - } - - exec.shutdown(); - } - -} +package com.baeldung.rxjava; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import hu.akarnokd.rxjava2.async.AsyncObservable; +import io.reactivex.Observable; + +public class AsyncAndSyncToObservableIntegrationTest { + + AtomicInteger counter = new AtomicInteger(); + Callable callable = () -> counter.incrementAndGet(); + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() { + + Observable source = Observable.fromCallable(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() { + + Observable source = AsyncObservable.start(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future future = executor.submit(callable); + Observable source = Observable.fromFuture(future); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + + executor.shutdown(); + } + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + + executor.shutdown(); + } + + /*Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { + List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); + ExecutorService exec = Executors.newSingleThreadExecutor(); + Callable> callable = () -> Observable.fromIterable(list); + Observable source = AsyncObservable.deferFuture(() -> exec.submit(callable)); + for (int i = 1; i < 4; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1, 2, 3); + } + + exec.shutdown(); + } + +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java diff --git a/rxjava/README.md b/rxjava/README.md deleted file mode 100644 index c9308ddcc6..0000000000 --- a/rxjava/README.md +++ /dev/null @@ -1,20 +0,0 @@ -## RxJava - -This module contains articles about RxJava. - -### Relevant articles: - -- [Dealing with Backpressure with RxJava](https://www.baeldung.com/rxjava-backpressure) -- [How to Test RxJava?](https://www.baeldung.com/rxjava-testing) -- [Implementing Custom Operators in RxJava](https://www.baeldung.com/rxjava-custom-operators) -- [Introduction to RxJava](https://www.baeldung.com/rx-java) -- [Observable Utility Operators in RxJava](https://www.baeldung.com/rxjava-observable-operators) -- [Introduction to rxjava-jdbc](https://www.baeldung.com/rxjava-jdbc) -- [Schedulers in RxJava](https://www.baeldung.com/rxjava-schedulers) -- [Mathematical and Aggregate Operators in RxJava](https://www.baeldung.com/rxjava-math) -- [Combining Observables in RxJava](https://www.baeldung.com/rxjava-combine-observables) -- [RxJava StringObservable](https://www.baeldung.com/rxjava-string) -- [Filtering Observables in RxJava](https://www.baeldung.com/rxjava-filtering) -- [RxJava One Observable, Multiple Subscribers](https://www.baeldung.com/rxjava-multiple-subscribers-observable) -- [Difference Between Flatmap and Switchmap in RxJava](https://www.baeldung.com/rxjava-flatmap-switchmap) -- More articles: [[next -->]](/rxjava-2) diff --git a/spring-5-data-reactive/README.md b/spring-5-data-reactive/README.md index 03bd323cb4..42fcba96f2 100644 --- a/spring-5-data-reactive/README.md +++ b/spring-5-data-reactive/README.md @@ -11,4 +11,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors) - [A Quick Look at R2DBC with Spring Data](https://www.baeldung.com/spring-data-r2dbc) - [Spring Data Reactive Repositories with Couchbase](https://www.baeldung.com/spring-data-reactive-couchbase) - diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java index 17eac7fee2..54f06d9c6c 100644 --- a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration; import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; @Configuration -//@EnableR2dbcRepositories(basePackages = "com.baeldung.r2dbc.repository") +@EnableR2dbcRepositories(basePackages = "com.baeldung.r2dbc.repository") public class R2DBCConfiguration extends AbstractR2dbcConfiguration { @Bean public H2ConnectionFactory connectionFactory() { diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java index 1926997e97..1e28cb3d07 100644 --- a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java @@ -4,10 +4,12 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; +import org.springframework.data.relational.core.mapping.Table; @Data @NoArgsConstructor @AllArgsConstructor +@Table public class Player { @Id Integer id; diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java index a31ef4458d..ffd2e98f8e 100644 --- a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java +++ b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java @@ -111,12 +111,12 @@ public class R2dbcApplicationIntegrationTest { private void insertPlayers() { List players = Arrays.asList( - new Player(1, "Kaka", 37), - new Player(2, "Messi", 32), - new Player(3, "Mbappé", 20), - new Player(4, "CR7", 34), - new Player(5, "Lewandowski", 30), - new Player(6, "Cavani", 32) + new Player(null, "Kaka", 37), + new Player(null, "Messi", 32), + new Player(null, "Mbappé", 20), + new Player(null, "CR7", 34), + new Player(null, "Lewandowski", 30), + new Player(null, "Cavani", 32) ); playerRepository.saveAll(players).subscribe(); diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index be21db481a..7417f39c21 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -46,14 +46,17 @@ org.jetbrains.kotlin kotlin-stdlib-jre8 + ${kotlin.version} org.jetbrains.kotlin kotlin-reflect + ${kotlin.version} com.fasterxml.jackson.module jackson-module-kotlin + ${jackson.version} @@ -170,7 +173,8 @@ 2.9.0 - 1.1.2 + 2.9.9 + 1.2.71 com.baeldung.Spring5Application 4.5.8 diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index 221c333d5b..bb308ae330 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -8,4 +8,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - [Logging Spring WebClient Calls](https://www.baeldung.com/spring-log-webclient-calls) - [Simultaneous Spring WebClient Calls](https://www.baeldung.com/spring-webclient-simultaneous-calls) - +- [Logging Spring WebClient Calls](https://www.baeldung.com/spring-log-webclient-calls) +- [Mocking a WebClient in Spring](https://www.baeldung.com/spring-mocking-webclient) diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java index 5d6c13bb0e..e2629053f1 100644 --- a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java @@ -71,5 +71,4 @@ public class LoginController { return "loginSuccess"; } - } diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index 6887f01753..91272593d3 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -99,6 +99,6 @@ - 2.2.0.M3 + 2.2.0.RELEASE diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java b/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java index 7dd3591cd6..abfe2e7807 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java @@ -25,6 +25,6 @@ public class ClientConfiguration { @Bean RSocketRequester rSocketRequester(RSocketStrategies rSocketStrategies) { - return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); + return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); } } diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java index ff00d5ec24..d22832b0fb 100644 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java @@ -13,7 +13,6 @@ import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.messaging.rsocket.RSocketRequester; import org.springframework.messaging.rsocket.RSocketRequester.RequestSpec; -import org.springframework.messaging.rsocket.RSocketRequester.ResponseSpec; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.FluxExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -34,15 +33,12 @@ public class MarketDataRestControllerIntegrationTest { @Mock private RequestSpec requestSpec; - @Mock - private ResponseSpec responseSpec; - @Test public void whenInitiatesRequest_ThenGetsResponse() throws Exception { when(rSocketRequester.route("currentMarketData")).thenReturn(requestSpec); - when(requestSpec.data(any())).thenReturn(responseSpec); + when(requestSpec.data(any())).thenReturn(requestSpec); MarketData marketData = new MarketData("X", 1); - when(responseSpec.retrieveMono(MarketData.class)).thenReturn(Mono.just(marketData)); + when(requestSpec.retrieveMono(MarketData.class)).thenReturn(Mono.just(marketData)); testClient.get() .uri("/current/{stock}", "X") @@ -56,8 +52,8 @@ public class MarketDataRestControllerIntegrationTest { @Test public void whenInitiatesFireAndForget_ThenGetsNoResponse() throws Exception { when(rSocketRequester.route("collectMarketData")).thenReturn(requestSpec); - when(requestSpec.data(any())).thenReturn(responseSpec); - when(responseSpec.send()).thenReturn(Mono.empty()); + when(requestSpec.data(any())).thenReturn(requestSpec); + when(requestSpec.send()).thenReturn(Mono.empty()); testClient.get() .uri("/collect") @@ -70,10 +66,10 @@ public class MarketDataRestControllerIntegrationTest { @Test public void whenInitiatesRequest_ThenGetsStream() throws Exception { when(rSocketRequester.route("feedMarketData")).thenReturn(requestSpec); - when(requestSpec.data(any())).thenReturn(responseSpec); + when(requestSpec.data(any())).thenReturn(requestSpec); MarketData firstMarketData = new MarketData("X", 1); MarketData secondMarketData = new MarketData("X", 2); - when(responseSpec.retrieveFlux(MarketData.class)).thenReturn(Flux.just(firstMarketData, secondMarketData)); + when(requestSpec.retrieveFlux(MarketData.class)).thenReturn(Flux.just(firstMarketData, secondMarketData)); FluxExchangeResult result = testClient.get() .uri("/feed/{stock}", "X") @@ -89,4 +85,4 @@ public class MarketDataRestControllerIntegrationTest { .thenCancel() .verify(); } -} \ No newline at end of file +} diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java index dcf3b82730..40ddc732ac 100644 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java @@ -92,7 +92,7 @@ public class MarketDataRSocketControllerLiveTest { @Bean @Lazy RSocketRequester rSocketRequester(RSocketStrategies rSocketStrategies) { - return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); + return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); } } -} \ No newline at end of file +} diff --git a/spring-5/README.md b/spring-5/README.md index 3f839a5bca..8a0cbe807e 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -15,4 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring ResponseStatusException](https://www.baeldung.com/spring-response-status-exception) - [Spring Assert Statements](https://www.baeldung.com/spring-assert) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) -- [Difference between \ vs \](https://www.baeldung.com/spring-contextannotation-contextcomponentscan) +- [Difference between vs ](https://www.baeldung.com/spring-contextannotation-contextcomponentscan) diff --git a/spring-all/README.md b/spring-all/README.md new file mode 100644 index 0000000000..2b9f61c76d --- /dev/null +++ b/spring-all/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [The @Scheduled Annotation in Spring](https://www.baeldung.com/spring-scheduled-tasks) diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/ErrorHandlingApp.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/ErrorHandlingApp.java new file mode 100644 index 0000000000..72a9ec8ad7 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/ErrorHandlingApp.java @@ -0,0 +1,26 @@ +package com.baeldung.springamqp.errorhandling; + +import com.baeldung.springamqp.errorhandling.producer.MessageProducer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +public class ErrorHandlingApp { + + @Autowired + MessageProducer messageProducer; + + public static void main(String[] args) { + SpringApplication.run(ErrorHandlingApp.class, args); + } + + @EventListener(ApplicationReadyEvent.class) + public void doSomethingAfterStartup() { + messageProducer.sendMessage(); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/DLXCustomAmqpConfiguration.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/DLXCustomAmqpConfiguration.java new file mode 100644 index 0000000000..708b08476d --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/DLXCustomAmqpConfiguration.java @@ -0,0 +1,55 @@ +package com.baeldung.springamqp.errorhandling.configuration; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.FanoutExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES_DLQ; + +@Configuration +@ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "dlx-custom") +public class DLXCustomAmqpConfiguration { + public static final String DLX_EXCHANGE_MESSAGES = QUEUE_MESSAGES + ".dlx"; + + @Bean + Queue messagesQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES) + .withArgument("x-dead-letter-exchange", DLX_EXCHANGE_MESSAGES) + .build(); + } + + @Bean + FanoutExchange deadLetterExchange() { + return new FanoutExchange(DLX_EXCHANGE_MESSAGES); + } + + @Bean + Queue deadLetterQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES_DLQ).build(); + } + + @Bean + Binding deadLetterBinding() { + return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()); + } + + @Bean + DirectExchange messagesExchange() { + return new DirectExchange(EXCHANGE_MESSAGES); + } + + @Bean + Binding bindingMessages() { + return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/DLXParkingLotAmqpConfiguration.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/DLXParkingLotAmqpConfiguration.java new file mode 100644 index 0000000000..bff325e657 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/DLXParkingLotAmqpConfiguration.java @@ -0,0 +1,72 @@ +package com.baeldung.springamqp.errorhandling.configuration; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.FanoutExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES_DLQ; + +@Configuration +@ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "parking-lot-dlx") +public class DLXParkingLotAmqpConfiguration { + public static final String DLX_EXCHANGE_MESSAGES = QUEUE_MESSAGES + ".dlx"; + public static final String QUEUE_PARKING_LOT = QUEUE_MESSAGES + ".parking-lot"; + public static final String EXCHANGE_PARKING_LOT = QUEUE_MESSAGES + "exchange.parking-lot"; + + @Bean + FanoutExchange parkingLotExchange() { + return new FanoutExchange(EXCHANGE_PARKING_LOT); + } + + @Bean + Queue parkingLotQueue() { + return QueueBuilder.durable(QUEUE_PARKING_LOT).build(); + } + + @Bean + Binding parkingLotBinding() { + return BindingBuilder.bind(parkingLotQueue()).to(parkingLotExchange()); + } + + @Bean + Queue messagesQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES) + .withArgument("x-dead-letter-exchange", DLX_EXCHANGE_MESSAGES) + .build(); + } + + @Bean + FanoutExchange deadLetterExchange() { + return new FanoutExchange(DLX_EXCHANGE_MESSAGES); + } + + @Bean + Queue deadLetterQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES_DLQ).build(); + } + + @Bean + Binding deadLetterBinding() { + return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()); + } + + @Bean + DirectExchange messagesExchange() { + return new DirectExchange(EXCHANGE_MESSAGES); + } + + @Bean + Binding bindingMessages() { + return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/FatalExceptionStrategyAmqpConfiguration.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/FatalExceptionStrategyAmqpConfiguration.java new file mode 100644 index 0000000000..dcd76d7f72 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/FatalExceptionStrategyAmqpConfiguration.java @@ -0,0 +1,63 @@ +package com.baeldung.springamqp.errorhandling.configuration; + +import com.baeldung.springamqp.errorhandling.errorhandler.CustomFatalExceptionStrategy; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.listener.ConditionalRejectingErrorHandler; +import org.springframework.amqp.rabbit.listener.FatalExceptionStrategy; +import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.ErrorHandler; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES; + +@Configuration +@ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "fatal-error-strategy") +public class FatalExceptionStrategyAmqpConfiguration { + + @Bean + public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory( + ConnectionFactory connectionFactory, + SimpleRabbitListenerContainerFactoryConfigurer configurer) { + SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + factory.setErrorHandler(errorHandler()); + return factory; + } + + @Bean + public ErrorHandler errorHandler() { + return new ConditionalRejectingErrorHandler(customExceptionStrategy()); + } + + @Bean + FatalExceptionStrategy customExceptionStrategy() { + return new CustomFatalExceptionStrategy(); + } + + @Bean + Queue messagesQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES) + .build(); + } + + @Bean + DirectExchange messagesExchange() { + return new DirectExchange(EXCHANGE_MESSAGES); + } + + @Bean + Binding bindingMessages() { + return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/ListenerErrorHandlerAmqpConfiguration.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/ListenerErrorHandlerAmqpConfiguration.java new file mode 100644 index 0000000000..8990381da2 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/ListenerErrorHandlerAmqpConfiguration.java @@ -0,0 +1,55 @@ +package com.baeldung.springamqp.errorhandling.configuration; + +import com.baeldung.springamqp.errorhandling.errorhandler.CustomErrorHandler; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.ErrorHandler; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES; + +@Configuration +@ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "listener-error") +public class ListenerErrorHandlerAmqpConfiguration { + + @Bean + public ErrorHandler errorHandler() { + return new CustomErrorHandler(); + } + + @Bean + public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory, + SimpleRabbitListenerContainerFactoryConfigurer configurer) { + SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); + configurer.configure(factory, connectionFactory); + factory.setErrorHandler(errorHandler()); + return factory; + } + + @Bean + Queue messagesQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES) + .build(); + } + + @Bean + DirectExchange messagesExchange() { + return new DirectExchange(EXCHANGE_MESSAGES); + } + + @Bean + Binding bindingMessages() { + return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/RoutingKeyDLQAmqpConfiguration.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/RoutingKeyDLQAmqpConfiguration.java new file mode 100644 index 0000000000..defabed306 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/RoutingKeyDLQAmqpConfiguration.java @@ -0,0 +1,55 @@ +package com.baeldung.springamqp.errorhandling.configuration; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.FanoutExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES_DLQ; + +@Configuration +@ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "routing-dlq") +public class RoutingKeyDLQAmqpConfiguration { + public static final String DLX_EXCHANGE_MESSAGES = QUEUE_MESSAGES + ".dlx"; + + @Bean + Queue messagesQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES) + .withArgument("x-dead-letter-exchange", DLX_EXCHANGE_MESSAGES) + .build(); + } + + @Bean + FanoutExchange deadLetterExchange() { + return new FanoutExchange(DLX_EXCHANGE_MESSAGES); + } + + @Bean + Queue deadLetterQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES_DLQ).build(); + } + + @Bean + Binding deadLetterBinding() { + return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()); + } + + @Bean + DirectExchange messagesExchange() { + return new DirectExchange(EXCHANGE_MESSAGES); + } + + @Bean + Binding bindingMessages() { + return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/SimpleDLQAmqpConfiguration.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/SimpleDLQAmqpConfiguration.java new file mode 100644 index 0000000000..ea129986ca --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/configuration/SimpleDLQAmqpConfiguration.java @@ -0,0 +1,43 @@ +package com.baeldung.springamqp.errorhandling.configuration; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "simple-dlq") +public class SimpleDLQAmqpConfiguration { + public static final String QUEUE_MESSAGES = "baeldung-messages-queue"; + public static final String QUEUE_MESSAGES_DLQ = QUEUE_MESSAGES + ".dlq"; + public static final String EXCHANGE_MESSAGES = "baeldung-messages-exchange"; + + @Bean + Queue messagesQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES) + .withArgument("x-dead-letter-exchange", "") + .withArgument("x-dead-letter-routing-key", QUEUE_MESSAGES_DLQ) + .build(); + } + + @Bean + Queue deadLetterQueue() { + return QueueBuilder.durable(QUEUE_MESSAGES_DLQ).build(); + } + + @Bean + DirectExchange messagesExchange() { + return new DirectExchange(EXCHANGE_MESSAGES); + } + + @Bean + Binding bindingMessages() { + return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/DLQCustomAmqpContainer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/DLQCustomAmqpContainer.java new file mode 100644 index 0000000000..62907abee9 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/DLQCustomAmqpContainer.java @@ -0,0 +1,35 @@ +package com.baeldung.springamqp.errorhandling.consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.amqp.rabbit.core.RabbitTemplate; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES_DLQ; +import static com.baeldung.springamqp.errorhandling.consumer.MessagesConsumer.HEADER_X_RETRIES_COUNT; + +public class DLQCustomAmqpContainer { + private static final Logger log = LoggerFactory.getLogger(DLQCustomAmqpContainer.class); + private final RabbitTemplate rabbitTemplate; + public static final int MAX_RETRIES_COUNT = 2; + + public DLQCustomAmqpContainer(RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + @RabbitListener(queues = QUEUE_MESSAGES_DLQ) + public void processFailedMessagesRetryHeaders(Message failedMessage) { + Integer retriesCnt = (Integer) failedMessage.getMessageProperties().getHeaders().get(HEADER_X_RETRIES_COUNT); + if (retriesCnt == null) + retriesCnt = 1; + if (retriesCnt > MAX_RETRIES_COUNT) { + log.info("Discarding message"); + return; + } + log.info("Retrying message for the {} time", retriesCnt); + failedMessage.getMessageProperties().getHeaders().put(HEADER_X_RETRIES_COUNT, ++retriesCnt); + rabbitTemplate.send(EXCHANGE_MESSAGES, failedMessage.getMessageProperties().getReceivedRoutingKey(), failedMessage); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/MessagesConsumer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/MessagesConsumer.java new file mode 100644 index 0000000000..17b65c58da --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/MessagesConsumer.java @@ -0,0 +1,63 @@ +package com.baeldung.springamqp.errorhandling.consumer; + +import com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration; +import com.baeldung.springamqp.errorhandling.errorhandler.BusinessException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MessagesConsumer { + public static final String HEADER_X_RETRIES_COUNT = "x-retries-count"; + + + private static final Logger log = LoggerFactory.getLogger(MessagesConsumer.class); + private final RabbitTemplate rabbitTemplate; + + public MessagesConsumer(RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + @RabbitListener(queues = SimpleDLQAmqpConfiguration.QUEUE_MESSAGES) + public void receiveMessage(Message message) throws BusinessException { + log.info("Received message: {}", message.toString()); + throw new BusinessException(); + } + + @Bean + @ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "simple-dlq") + public SimpleDLQAmqpContainer simpleAmqpContainer() { + return new SimpleDLQAmqpContainer(rabbitTemplate); + } + + @Bean + @ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "routing-dlq") + public RoutingDLQAmqpContainer routingDLQAmqpContainer() { + return new RoutingDLQAmqpContainer(rabbitTemplate); + } + + @Bean + @ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "dlx-custom") + public DLQCustomAmqpContainer dlqAmqpContainer() { + return new DLQCustomAmqpContainer(rabbitTemplate); + } + + @Bean + @ConditionalOnProperty( + value = "amqp.configuration.current", + havingValue = "parking-lot-dlx") + public ParkingLotDLQAmqpContainer parkingLotDLQAmqpContainer() { + return new ParkingLotDLQAmqpContainer(rabbitTemplate); + } +} \ No newline at end of file diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/ParkingLotDLQAmqpContainer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/ParkingLotDLQAmqpContainer.java new file mode 100644 index 0000000000..34dccd408a --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/ParkingLotDLQAmqpContainer.java @@ -0,0 +1,43 @@ +package com.baeldung.springamqp.errorhandling.consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.amqp.rabbit.core.RabbitTemplate; + +import static com.baeldung.springamqp.errorhandling.configuration.DLXParkingLotAmqpConfiguration.EXCHANGE_PARKING_LOT; +import static com.baeldung.springamqp.errorhandling.configuration.DLXParkingLotAmqpConfiguration.QUEUE_PARKING_LOT; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES_DLQ; +import static com.baeldung.springamqp.errorhandling.consumer.MessagesConsumer.HEADER_X_RETRIES_COUNT; + +public class ParkingLotDLQAmqpContainer { + private static final Logger log = LoggerFactory.getLogger(ParkingLotDLQAmqpContainer.class); + private final RabbitTemplate rabbitTemplate; + public static final int MAX_RETRIES_COUNT = 2; + + public ParkingLotDLQAmqpContainer(RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + @RabbitListener(queues = QUEUE_MESSAGES_DLQ) + public void processFailedMessagesRetryWithParkingLot(Message failedMessage) { + Integer retriesCnt = (Integer) failedMessage.getMessageProperties().getHeaders().get(HEADER_X_RETRIES_COUNT); + if (retriesCnt == null) + retriesCnt = 1; + if (retriesCnt > MAX_RETRIES_COUNT) { + log.info("Sending message to the parking lot queue"); + rabbitTemplate.send(EXCHANGE_PARKING_LOT, failedMessage.getMessageProperties().getReceivedRoutingKey(), failedMessage); + return; + } + log.info("Retrying message for the {} time", retriesCnt); + failedMessage.getMessageProperties().getHeaders().put(HEADER_X_RETRIES_COUNT, ++retriesCnt); + rabbitTemplate.send(EXCHANGE_MESSAGES, failedMessage.getMessageProperties().getReceivedRoutingKey(), failedMessage); + } + + @RabbitListener(queues = QUEUE_PARKING_LOT) + public void processParkingLotQueue(Message failedMessage) { + log.info("Received message in parking lot queue {}", failedMessage.toString()); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/RoutingDLQAmqpContainer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/RoutingDLQAmqpContainer.java new file mode 100644 index 0000000000..fedce76880 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/RoutingDLQAmqpContainer.java @@ -0,0 +1,33 @@ +package com.baeldung.springamqp.errorhandling.consumer; + +import com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration; +import com.baeldung.springamqp.errorhandling.errorhandler.BusinessException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.amqp.rabbit.core.RabbitTemplate; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES_DLQ; + +public class RoutingDLQAmqpContainer { + private static final Logger log = LoggerFactory.getLogger(RoutingDLQAmqpContainer.class); + private final RabbitTemplate rabbitTemplate; + + public RoutingDLQAmqpContainer(RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + @RabbitListener(queues = SimpleDLQAmqpConfiguration.QUEUE_MESSAGES) + public void receiveMessage(Message message) throws BusinessException { + log.info("Received message: {}", message.toString()); + throw new BusinessException(); + } + + @RabbitListener(queues = QUEUE_MESSAGES_DLQ) + public void processFailedMessagesRequeue(Message failedMessage) { + log.info("Received failed message, requeueing: {}", failedMessage.toString()); + rabbitTemplate.send(EXCHANGE_MESSAGES, failedMessage.getMessageProperties().getReceivedRoutingKey(), failedMessage); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/SimpleDLQAmqpContainer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/SimpleDLQAmqpContainer.java new file mode 100644 index 0000000000..6f9da7b587 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/consumer/SimpleDLQAmqpContainer.java @@ -0,0 +1,31 @@ +package com.baeldung.springamqp.errorhandling.consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.amqp.rabbit.core.RabbitTemplate; + +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES; +import static com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration.QUEUE_MESSAGES_DLQ; + +public class SimpleDLQAmqpContainer { + private static final Logger log = LoggerFactory.getLogger(SimpleDLQAmqpContainer.class); + private final RabbitTemplate rabbitTemplate; + + public SimpleDLQAmqpContainer(RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + @RabbitListener(queues = QUEUE_MESSAGES_DLQ) + public void processFailedMessages(Message message) { + log.info("Received failed message: {}", message.toString()); + } + + @RabbitListener(queues = QUEUE_MESSAGES_DLQ) + public void processFailedMessagesRequeue(Message failedMessage) { + log.info("Received failed message, requeueing: {}", failedMessage.toString()); + log.info("Received failed message, requeueing: {}", failedMessage.getMessageProperties().getReceivedRoutingKey()); + rabbitTemplate.send(EXCHANGE_MESSAGES, failedMessage.getMessageProperties().getReceivedRoutingKey(), failedMessage); + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/BusinessException.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/BusinessException.java new file mode 100644 index 0000000000..faec96e2aa --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/BusinessException.java @@ -0,0 +1,4 @@ +package com.baeldung.springamqp.errorhandling.errorhandler; + +public class BusinessException extends Exception { +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/CustomErrorHandler.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/CustomErrorHandler.java new file mode 100644 index 0000000000..5c5e9cdf13 --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/CustomErrorHandler.java @@ -0,0 +1,14 @@ +package com.baeldung.springamqp.errorhandling.errorhandler; + +import org.springframework.amqp.AmqpRejectAndDontRequeueException; +import org.springframework.util.ErrorHandler; + +public class CustomErrorHandler implements ErrorHandler { + + @Override + public void handleError(Throwable t) { + if (!(t.getCause() instanceof BusinessException)) { + throw new AmqpRejectAndDontRequeueException("Error Handler converted exception to fatal", t); + } + } +} diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/CustomFatalExceptionStrategy.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/CustomFatalExceptionStrategy.java new file mode 100644 index 0000000000..e14be4e73c --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/errorhandler/CustomFatalExceptionStrategy.java @@ -0,0 +1,10 @@ +package com.baeldung.springamqp.errorhandling.errorhandler; + +import org.springframework.amqp.rabbit.listener.ConditionalRejectingErrorHandler; + +public class CustomFatalExceptionStrategy extends ConditionalRejectingErrorHandler.DefaultExceptionStrategy { + @Override + public boolean isFatal(Throwable t) { + return !(t.getCause() instanceof BusinessException); + } +} \ No newline at end of file diff --git a/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/producer/MessageProducer.java b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/producer/MessageProducer.java new file mode 100644 index 0000000000..c14fd5bf3b --- /dev/null +++ b/spring-amqp/src/main/java/com/baeldung/springamqp/errorhandling/producer/MessageProducer.java @@ -0,0 +1,24 @@ +package com.baeldung.springamqp.errorhandling.producer; + +import com.baeldung.springamqp.errorhandling.configuration.SimpleDLQAmqpConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.stereotype.Service; + +@Service +public class MessageProducer { + + private static final Logger log = LoggerFactory.getLogger(MessageProducer.class); + private int messageNumber = 0; + private final RabbitTemplate rabbitTemplate; + + public MessageProducer(final RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + public void sendMessage() { + log.info("Sending message..."); + rabbitTemplate.convertAndSend(SimpleDLQAmqpConfiguration.EXCHANGE_MESSAGES, SimpleDLQAmqpConfiguration.QUEUE_MESSAGES, "Some message id:" + messageNumber++); + } +} \ No newline at end of file diff --git a/spring-amqp/src/main/resources/application.properties b/spring-amqp/src/main/resources/application.properties new file mode 100644 index 0000000000..c0c1cf1b47 --- /dev/null +++ b/spring-amqp/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.rabbitmq.listener.simple.default-requeue-rejected=false +spring.main.allow-bean-definition-overriding=true +amqp.configuration.current=parking-lot-dlx \ No newline at end of file diff --git a/spring-batch/README.md b/spring-batch/README.md index 95abbaf931..9e09612490 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring Batch - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) - [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) +- [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index 48d3baeae3..e6d7cee6f2 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -78,36 +79,25 @@ org.springframework.boot spring-boot-starter-batch - ${spring.boot.version} org.hsqldb hsqldb - 2.5.0 runtime - + org.awaitility awaitility ${awaitility.version} test - - - org.springframework.boot - spring-boot-starter-test - ${spring.boot.version} - test - - 5.2.0.RELEASE 4.2.0.RELEASE - 2.1.9.RELEASE 3.15.1 4.1 2.3.1 diff --git a/spring-boot-admin/README.md b/spring-boot-admin/README.md index ac4d781d0e..1a7acef6c1 100644 --- a/spring-boot-admin/README.md +++ b/spring-boot-admin/README.md @@ -24,3 +24,4 @@ and the mail configuration from application.properties ### Relevant Articles: - [A Guide to Spring Boot Admin](https://www.baeldung.com/spring-boot-admin) +- [Changing the Logging Level at the Runtime for a Spring Boot Application](https://www.baeldung.com/spring-boot-changing-log-level-at-runtime) diff --git a/spring-boot-admin/pom.xml b/spring-boot-admin/pom.xml index 1c933723e7..c553790359 100644 --- a/spring-boot-admin/pom.xml +++ b/spring-boot-admin/pom.xml @@ -8,8 +8,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT @@ -17,20 +17,4 @@ spring-boot-admin-client - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - - - 2.1.8.RELEASE - - - \ No newline at end of file + diff --git a/spring-boot-artifacts/README.md b/spring-boot-artifacts/README.md index 4025e43a65..876954e858 100644 --- a/spring-boot-artifacts/README.md +++ b/spring-boot-artifacts/README.md @@ -7,4 +7,5 @@ This module contains articles about configuring the Spring Boot build process. - [Create a Fat Jar App with Spring Boot](https://www.baeldung.com/deployable-fat-jar-spring-boot) - [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters) - [Introduction to WebJars](https://www.baeldung.com/maven-webjars) - - [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper) \ No newline at end of file + - [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper) + - [Running a Spring Boot App with Maven vs an Executable War/Jar](https://www.baeldung.com/spring-boot-run-maven-vs-executable-jar) diff --git a/spring-boot-autoconfiguration/README.md b/spring-boot-autoconfiguration/README.md index 180d857d52..b3a50ad7a5 100644 --- a/spring-boot-autoconfiguration/README.md +++ b/spring-boot-autoconfiguration/README.md @@ -10,4 +10,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Create a Custom Auto-Configuration with Spring Boot](https://www.baeldung.com/spring-boot-custom-auto-configuration) - [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner) - [A Guide to Spring Boot Configuration Metadata](https://www.baeldung.com/spring-boot-configuration-metadata) - diff --git a/spring-boot-configuration/README.md b/spring-boot-configuration/README.md index c449538a9d..af634aa5f4 100644 --- a/spring-boot-configuration/README.md +++ b/spring-boot-configuration/README.md @@ -3,3 +3,4 @@ This module contains articles about Spring Boot Configuration. ### Relevant Articles: +- [Unable to Find @SpringBootConfiguration with @DataJpaTest](https://www.baeldung.com/spring-boot-unable-to-find-springbootconfiguration-with-datajpatest) diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 91cc41d669..1528853b0c 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -7,24 +7,12 @@ greeter-spring-boot-sample-app - spring-boot-custom-starter + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT ../../spring-boot-custom-starter - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - com.baeldung @@ -51,8 +39,7 @@ - 1.5.15.RELEASE 0.0.1-SNAPSHOT - \ No newline at end of file + diff --git a/spring-boot-data/README.md b/spring-boot-data/README.md index 513c5fed18..eb3cd5bbaa 100644 --- a/spring-boot-data/README.md +++ b/spring-boot-data/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring Boot with Spring Data - [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates) - [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) - [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) +- [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java index 8e4ee76a25..87656f66a6 100644 --- a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java @@ -1,12 +1,15 @@ package com.baeldung.disableautoconfig; +import org.javers.spring.boot.sql.JaversSqlAutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, + JaversSqlAutoConfiguration.class, SpringDataWebAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class SpringDataJPA { diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java index 865c137a8d..0845acee6e 100644 --- a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java @@ -3,9 +3,11 @@ package com.baeldung.disableautoconfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; -@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class}) +@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + SpringDataWebAutoConfiguration.class}) public class SpringDataMongoDB { public static void main(String[] args) { diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java index 9ec831c446..cd8cb0de09 100644 --- a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java @@ -4,8 +4,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration; +import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; -@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class}) +@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, + SpringDataWebAutoConfiguration.class}) public class SpringDataRedis { public static void main(String[] args) { diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/README.md b/spring-boot-data/src/main/java/com/baeldung/javers/README.md new file mode 100644 index 0000000000..4f8dd4abff --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/javers/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) diff --git a/spring-boot-deployment/README.md b/spring-boot-deployment/README.md index 6171decf2d..b6aa468098 100644 --- a/spring-boot-deployment/README.md +++ b/spring-boot-deployment/README.md @@ -6,4 +6,5 @@ This module contains articles about deployment of a Spring Boot Application - [Deploy a Spring Boot WAR into a Tomcat Server](https://www.baeldung.com/spring-boot-war-tomcat-deploy) - [Spring Boot Console Application](https://www.baeldung.com/spring-boot-console-app) - [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) - - [Comparing Embedded Servlet Containers in Spring Boot](https://www.baeldung.com/spring-boot-servlet-containers) \ No newline at end of file + - [Comparing Embedded Servlet Containers in Spring Boot](https://www.baeldung.com/spring-boot-servlet-containers) + - [Graceful Shutdown of a Spring Boot Application](https://www.baeldung.com/spring-boot-graceful-shutdown) diff --git a/spring-boot-di/README.MD b/spring-boot-di/README.MD index 6e2c495b88..cbd42c5609 100644 --- a/spring-boot-di/README.MD +++ b/spring-boot-di/README.MD @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) +- [Spring @ComponentScan – Filter Types](https://www.baeldung.com/spring-componentscan-filter-type) diff --git a/spring-boot-kotlin/pom.xml b/spring-boot-kotlin/pom.xml index 25508c52b9..ccb1585a75 100644 --- a/spring-boot-kotlin/pom.xml +++ b/spring-boot-kotlin/pom.xml @@ -30,19 +30,6 @@ - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - spring-snapshots @@ -81,7 +68,6 @@ org.springframework.boot spring-boot-starter-webflux - ${spring-boot.version} com.fasterxml.jackson.module @@ -160,7 +146,6 @@ 1.0.0.M7 1.0.0.BUILD-SNAPSHOT 1.2.1 - 2.2.0.M2 diff --git a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml index de2946fbb2..a64ebc246a 100644 --- a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml +++ b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -10,22 +10,10 @@ com.baeldung - spring-boot-parent - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - org.springframework.boot @@ -35,7 +23,6 @@ 1.8 - 2.1.5.RELEASE diff --git a/spring-boot-properties/pom.xml b/spring-boot-properties/pom.xml index ccb9204d96..5e65aadc28 100644 --- a/spring-boot-properties/pom.xml +++ b/spring-boot-properties/pom.xml @@ -32,11 +32,6 @@ org.springframework.cloud spring-cloud-starter - - org.springframework.boot - spring-boot-starter-test - test - com.google.guava guava diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java index c15fcbd352..a506060d1c 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java @@ -16,7 +16,7 @@ public class ChildConfig2 { } @Bean - public static PropertyPlaceholderConfigurer configurer() { + public static PropertyPlaceholderConfigurer properties() { final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocations(new ClassPathResource("child.properties")); return ppc; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java index ddb59a5309..f5376e0c8e 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java @@ -16,7 +16,7 @@ public class ParentConfig2 { } @Bean - public static PropertyPlaceholderConfigurer configurer() { + public static PropertyPlaceholderConfigurer properties() { final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocations(new ClassPathResource("parent.properties")); return ppc; diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index ffac9335fd..3909a99c65 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -10,6 +10,7 @@ This module contains articles about Spring Boot RESTful APIs. - [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) - [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) +- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) ### E-book diff --git a/spring-boot-springdoc/pom.xml b/spring-boot-springdoc/pom.xml new file mode 100644 index 0000000000..a818db6e53 --- /dev/null +++ b/spring-boot-springdoc/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + com.baeldung + spring-boot-springdoc + 0.0.1-SNAPSHOT + spring-boot-springdoc + Project for Springdoc integration + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springdoc + springdoc-openapi-core + 1.1.45 + + + org.springdoc + springdoc-openapi-ui + 1.1.45 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + integration + + + + org.springframework.boot + spring-boot-maven-plugin + 2.1.8.RELEASE + + + pre-integration-test + + start + + + + post-integration-test + + stop + + + + + + org.springdoc + springdoc-openapi-maven-plugin + 0.2 + + + integration-test + + generate + + + + + http://localhost:8080/api-docs + openapi.json + ${project.build.directory} + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/SpringdocApplication.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/SpringdocApplication.java new file mode 100644 index 0000000000..45c7c23621 --- /dev/null +++ b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/SpringdocApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.springdoc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringdocApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringdocApplication.class, args); + } + +} diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java new file mode 100644 index 0000000000..4d7d9e3d85 --- /dev/null +++ b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java @@ -0,0 +1,73 @@ +package com.baeldung.springdoc.controller; + +import java.util.Collection; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.springdoc.exception.BookNotFoundException; +import com.baeldung.springdoc.model.Book; +import com.baeldung.springdoc.repository.BookRepository; + +@RestController +@RequestMapping("/api/book") +public class BookController { + + @Autowired + private BookRepository repository; + + @GetMapping("/{id}") + public Book findById(@PathVariable long id) { + return repository.findById(id) + .orElseThrow(() -> new BookNotFoundException()); + } + + @GetMapping("/") + public Collection findBooks() { + return repository.getBooks(); + } + + @PutMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public Book updateBook(@PathVariable("id") final String id, @RequestBody final Book book) { + return book; + } + + @PatchMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public Book patchBook(@PathVariable("id") final String id, @RequestBody final Book book) { + return book; + } + + @PostMapping("/") + @ResponseStatus(HttpStatus.CREATED) + public Book postBook(@NotNull @Valid @RequestBody final Book book) { + return book; + } + + @RequestMapping(method = RequestMethod.HEAD, value = "/") + @ResponseStatus(HttpStatus.OK) + public Book headBook() { + return new Book(); + } + + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.OK) + public long deleteBook(@PathVariable final long id) { + return id; + } +} diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/BookNotFoundException.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/BookNotFoundException.java new file mode 100644 index 0000000000..632cb683bc --- /dev/null +++ b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/BookNotFoundException.java @@ -0,0 +1,10 @@ +package com.baeldung.springdoc.exception; + +@SuppressWarnings("serial") +public class BookNotFoundException extends RuntimeException { + + public BookNotFoundException() { + + } + +} \ No newline at end of file diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/GlobalControllerExceptionHandler.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/GlobalControllerExceptionHandler.java new file mode 100644 index 0000000000..c829072236 --- /dev/null +++ b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/exception/GlobalControllerExceptionHandler.java @@ -0,0 +1,24 @@ +package com.baeldung.springdoc.exception; + +import org.springframework.core.convert.ConversionFailedException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalControllerExceptionHandler { + + @ExceptionHandler(ConversionFailedException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleConnversion(RuntimeException ex) { + return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(BookNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseEntity handleBookNotFound(RuntimeException ex) { + return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); + } +} diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java new file mode 100644 index 0000000000..8f678a7ec2 --- /dev/null +++ b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java @@ -0,0 +1,41 @@ +package com.baeldung.springdoc.model; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +public class Book { + + private long id; + + @NotBlank + @Size(min = 0, max = 20) + private String title; + + @NotBlank + @Size(min = 0, max = 30) + private String author; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} diff --git a/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java new file mode 100644 index 0000000000..4040ba28c2 --- /dev/null +++ b/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/repository/BookRepository.java @@ -0,0 +1,28 @@ +package com.baeldung.springdoc.repository; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import org.springframework.stereotype.Repository; + +import com.baeldung.springdoc.model.Book; + +@Repository +public class BookRepository { + + private Map books = new HashMap<>(); + + public Optional findById(long id) { + return Optional.ofNullable(books.get(id)); + } + + public void add(Book book) { + books.put(book.getId(), book); + } + + public Collection getBooks() { + return books.values(); + } +} diff --git a/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-springdoc/src/main/resources/application.properties new file mode 100644 index 0000000000..f03e90feb6 --- /dev/null +++ b/spring-boot-springdoc/src/main/resources/application.properties @@ -0,0 +1,5 @@ +# custom path for swagger-ui +springdoc.swagger-ui.path=/swagger-ui-custom.html + +# custom path for api docs +springdoc.api-docs.path=/api-docs diff --git a/rxjava/src/main/resources/logback.xml b/spring-boot-springdoc/src/main/resources/logback.xml similarity index 74% rename from rxjava/src/main/resources/logback.xml rename to spring-boot-springdoc/src/main/resources/logback.xml index 7d900d8ea8..6a07b178e9 100644 --- a/rxjava/src/main/resources/logback.xml +++ b/spring-boot-springdoc/src/main/resources/logback.xml @@ -7,6 +7,9 @@ + + + diff --git a/spring-boot-springdoc/src/test/java/com/baeldung/springdoc/SpringContextIntegrationTest.java b/spring-boot-springdoc/src/test/java/com/baeldung/springdoc/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..58c12dc3bc --- /dev/null +++ b/spring-boot-springdoc/src/test/java/com/baeldung/springdoc/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung.springdoc; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } + +} 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 049b118b12..eb886338a0 100644 --- a/spring-boot/src/main/java/org/baeldung/model/User.java +++ b/spring-boot/src/main/java/org/baeldung/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.model; +package org.baeldung.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; 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 0113c4c5d4..752664cd5d 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -1,6 +1,6 @@ package org.baeldung.repository; -import org.baeldung.caching.model.User; +import org.baeldung.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -15,7 +15,6 @@ import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.stream.Stream; @Repository("userRepository") public interface UserRepository extends JpaRepository { 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 54ce3b4bf3..ea7f118967 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -1,19 +1,17 @@ package org.baeldung.repository; import org.baeldung.boot.config.H2JpaConfig; -import org.baeldung.caching.model.User; +import org.baeldung.model.User; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; diff --git a/spring-cloud/spring-cloud-stream/README.md b/spring-cloud/spring-cloud-stream/README.md index fd1eeccfda..1fb0647ee3 100644 --- a/spring-cloud/spring-cloud-stream/README.md +++ b/spring-cloud/spring-cloud-stream/README.md @@ -4,3 +4,4 @@ This module contains articles about Spring Cloud Stream ## Relevant Articles - [Introduction to Spring Cloud Stream](http://www.baeldung.com/spring-cloud-stream) +- [Integrating Spring with AWS Kinesis](https://www.baeldung.com/spring-aws-kinesis) diff --git a/spring-cloud/spring-cloud-zuul-fallback/README.md b/spring-cloud/spring-cloud-zuul-fallback/README.md index 2f13c1923b..de5cfcef4b 100644 --- a/spring-cloud/spring-cloud-zuul-fallback/README.md +++ b/spring-cloud/spring-cloud-zuul-fallback/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Fallback for Zuul Route](TODO) +- [Fallback for Zuul Route](https://www.baeldung.com/spring-zuul-fallback-route) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index bcb1ce1fb4..ec6eb91306 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -15,4 +15,5 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- More articles: [[<-- prev]](/spring-core) \ No newline at end of file +- [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) +- More articles: [[<-- prev]](/spring-core) diff --git a/spring-core/README.md b/spring-core/README.md index 6d274e89f0..1f3dcb783b 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -4,9 +4,9 @@ This module contains articles about core Spring functionality ### Relevant Articles: - [Wiring in Spring: @Autowired, @Resource and @Inject](https://www.baeldung.com/spring-annotations-resource-inject-autowire) -- [Constructor Injection in Spring with Lombok](httsp://www.baeldung.com/spring-injection-lombok) +- [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) - [Introduction to Spring’s StreamUtils](https://www.baeldung.com/spring-stream-utils) -- [XML-Based Injection in Spring](httsp://www.baeldung.com/spring-xml-injection) +- [XML-Based Injection in Spring](https://www.baeldung.com/spring-xml-injection) - [A Quick Guide to the Spring @Lazy Annotation](https://www.baeldung.com/spring-lazy-annotation) - [BeanNameAware and BeanFactoryAware Interfaces in Spring](https://www.baeldung.com/spring-bean-name-factory-aware) - [Access a File from the Classpath in a Spring Application](https://www.baeldung.com/spring-classpath-file-access) diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java index ef86c2f36d..2d3dbc4c74 100644 --- a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java @@ -36,17 +36,17 @@ public class IntegrationTest { @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetJohn() throws Exception { // Get John - mockMvc.perform(get("/personQuery?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + mockMvc.perform(get("/users?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("John"))) .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) - .andExpect(jsonPath("$[0].address.country", is("Fake Country"))); + .andExpect(jsonPath("$[0].address.country", is("Spain"))); } @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetLisa() throws Exception { // Get Lisa - mockMvc.perform(get("/personQuery?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + mockMvc.perform(get("/users?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("Lisa"))) .andExpect(jsonPath("$[0].address.address", is("Real Street 1"))) - .andExpect(jsonPath("$[0].address.country", is("Real Country"))); + .andExpect(jsonPath("$[0].address.country", is("Germany"))); } } diff --git a/spring-ejb/README.md b/spring-ejb/README.md index 6c63c2709f..423d55ea22 100644 --- a/spring-ejb/README.md +++ b/spring-ejb/README.md @@ -6,7 +6,6 @@ This module contains articles about Spring with EJB - [Guide to EJB Set-up](https://www.baeldung.com/ejb-intro) - [Java EE Session Beans](https://www.baeldung.com/ejb-session-beans) -- [Introduction to EJB JNDI Lookup on WildFly Application Server](httpss://www.baeldung.com/wildfly-ejb-jndi) - [A Guide to Message Driven Beans in EJB](https://www.baeldung.com/ejb-message-driven-beans) - [Integration Guide for Spring and EJB](https://www.baeldung.com/spring-ejb) - [Singleton Session Bean in Java EE](https://www.baeldung.com/java-ee-singleton-session-bean) diff --git a/spring-ejb/pom.xml b/spring-ejb/pom.xml index 712bfc66ab..4422223c6f 100755 --- a/spring-ejb/pom.xml +++ b/spring-ejb/pom.xml @@ -4,6 +4,7 @@ 4.0.0 com.baeldung.spring.ejb spring-ejb + 1.0.0-SNAPSHOT spring-ejb pom Spring EJB Tutorial @@ -12,6 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-ejb/spring-ejb-client/README.md b/spring-ejb/spring-ejb-client/README.md new file mode 100644 index 0000000000..9addac7867 --- /dev/null +++ b/spring-ejb/spring-ejb-client/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to EJB JNDI Lookup on WildFly Application Server](https://www.baeldung.com/wildfly-ejb-jndi) diff --git a/spring-ejb/spring-ejb-client/pom.xml b/spring-ejb/spring-ejb-client/pom.xml index e0348d5ae3..2dd3120532 100644 --- a/spring-ejb/spring-ejb-client/pom.xml +++ b/spring-ejb/spring-ejb-client/pom.xml @@ -12,13 +12,13 @@ spring-ejb 1.0.0-SNAPSHOT - - + + org.springframework.boot spring-boot-dependencies - 2.0.4.RELEASE + ${spring-boot.version} pom import @@ -61,9 +61,13 @@ org.springframework.boot spring-boot-maven-plugin - 2.0.4.RELEASE + ${spring-boot.version} + + 2.0.4.RELEASE + + diff --git a/spring-ejb/spring-ejb-remote/README.md b/spring-ejb/spring-ejb-remote/README.md new file mode 100644 index 0000000000..9addac7867 --- /dev/null +++ b/spring-ejb/spring-ejb-remote/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to EJB JNDI Lookup on WildFly Application Server](https://www.baeldung.com/wildfly-ejb-jndi) diff --git a/spring-freemarker/README.md b/spring-freemarker/README.md index d9dfe16fbe..941777207f 100644 --- a/spring-freemarker/README.md +++ b/spring-freemarker/README.md @@ -5,4 +5,3 @@ This module contains articles about Spring with FreeMarker ### Relevant Articles: - [Introduction to Using FreeMarker in Spring MVC](https://www.baeldung.com/freemarker-in-spring-mvc-tutorial) - [FreeMarker Common Operations](https://www.baeldung.com/freemarker-operations) - diff --git a/spring-integration/README.md b/spring-integration/README.md index 2e719a8674..ad46082a04 100644 --- a/spring-integration/README.md +++ b/spring-integration/README.md @@ -7,6 +7,7 @@ This module contains articles about Spring Integration - [Security In Spring Integration](https://www.baeldung.com/spring-integration-security) - [Spring Integration Java DSL](https://www.baeldung.com/spring-integration-java-dsl) - [Using Subflows in Spring Integration](https://www.baeldung.com/spring-integration-subflows) +- [Transaction Support in Spring Integration](https://www.baeldung.com/spring-integration-transaction) ### Running the Sample Executing the `mvn exec:java` maven command (either from the command line or from an IDE) will start up the application. Follow the command prompt for further instructions. diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index e053ee7b4b..cf80ac4069 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -222,12 +222,12 @@ - 2.27 + 2.29.1 1.6.1 4.4.9 4.5.5 4.0.0 - 1.58 + 2.25.1 3.10.0 1.5.10.RELEASE diff --git a/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java index 990279a481..8f40636d01 100644 --- a/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java +++ b/spring-jersey/src/test/java/com/baeldung/clientrx/ClientOrchestrationIntegrationTest.java @@ -41,9 +41,9 @@ public class ClientOrchestrationIntegrationTest { private Client client = ClientBuilder.newClient(); - private WebTarget userIdService = client.target("http://localhost:8080/id-service/ids"); - private WebTarget nameService = client.target("http://localhost:8080/name-service/users/{userId}/name"); - private WebTarget hashService = client.target("http://localhost:8080/hash-service/{rawValue}"); + private WebTarget userIdService = client.target("http://localhost:{port}/id-service/ids"); + private WebTarget nameService = client.target("http://localhost:{port}/name-service/users/{userId}/name"); + private WebTarget hashService = client.target("http://localhost:{port}/hash-service/{rawValue}"); private Logger logger = LoggerFactory.getLogger(ClientOrchestrationIntegrationTest.class); @@ -54,7 +54,7 @@ public class ClientOrchestrationIntegrationTest { private List expectedHashValues = Arrays.asList("roht1", "kluh2", "WodiwKcalb3", "RehtnapKclab4", "kciteht5", "eyekwah6"); @Rule - public WireMockRule wireMockServer = new WireMockRule(); + public WireMockRule wireMockServer = new WireMockRule(0); @Before public void setup() { @@ -83,19 +83,19 @@ public class ClientOrchestrationIntegrationTest { final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls - userIdService.request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback>() { + getUserIdService().request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback>() { @Override public void completed(List employeeIds) { logger.info("[CallbackExample] id-service result: {}", employeeIds); employeeIds.forEach((id) -> { // for each employee ID, get the name - nameService.resolveTemplate("userId", id).request().async().get(new InvocationCallback() { + getNameService().resolveTemplate("userId", id).request().async().get(new InvocationCallback() { @Override public void completed(String response) { logger.info("[CallbackExample] name-service result: {}", response); - hashService.resolveTemplate("rawValue", response + id).request().async().get(new InvocationCallback() { + getHashService().resolveTemplate("rawValue", response + id).request().async().get(new InvocationCallback() { @Override public void completed(String response) { logger.info("[CallbackExample] hash-service result: {}", response); @@ -144,7 +144,7 @@ public class ClientOrchestrationIntegrationTest { final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls - CompletionStage> userIdStage = userIdService.request().accept(MediaType.APPLICATION_JSON).rx().get(new GenericType>() { + CompletionStage> userIdStage = getUserIdService().request().accept(MediaType.APPLICATION_JSON).rx().get(new GenericType>() { }).exceptionally((throwable) -> { logger.warn("[CompletionStageExample] An error has occurred"); return null; @@ -153,11 +153,11 @@ public class ClientOrchestrationIntegrationTest { userIdStage.thenAcceptAsync(employeeIds -> { logger.info("[CompletionStageExample] id-service result: {}", employeeIds); employeeIds.forEach((Long id) -> { - CompletableFuture completable = nameService.resolveTemplate("userId", id).request().rx().get(String.class).toCompletableFuture(); + CompletableFuture completable = getNameService().resolveTemplate("userId", id).request().rx().get(String.class).toCompletableFuture(); completable.thenAccept((String userName) -> { logger.info("[CompletionStageExample] name-service result: {}", userName); - hashService.resolveTemplate("rawValue", userName + id).request().rx().get(String.class).toCompletableFuture().thenAcceptAsync(hashValue -> { + getHashService().resolveTemplate("rawValue", userName + id).request().rx().get(String.class).toCompletableFuture().thenAcceptAsync(hashValue -> { logger.info("[CompletionStageExample] hash-service result: {}", hashValue); receivedHashValues.add(hashValue); completionTracker.countDown(); @@ -191,18 +191,18 @@ public class ClientOrchestrationIntegrationTest { final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls - Observable> observableUserIdService = userIdService.register(RxObservableInvokerProvider.class).request().accept(MediaType.APPLICATION_JSON).rx(RxObservableInvoker.class).get(new GenericType>() { + Observable> observableUserIdService = getUserIdService().register(RxObservableInvokerProvider.class).request().accept(MediaType.APPLICATION_JSON).rx(RxObservableInvoker.class).get(new GenericType>() { }).asObservable(); observableUserIdService.subscribe((List employeeIds) -> { logger.info("[ObservableExample] id-service result: {}", employeeIds); - Observable.from(employeeIds).subscribe(id -> nameService.register(RxObservableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the name for the given + Observable.from(employeeIds).subscribe(id -> getNameService().register(RxObservableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the name for the given // userId .doOnError((throwable) -> { logger.warn("[ObservableExample] An error has occurred in the username request step {}", throwable.getMessage()); }).subscribe(userName -> { logger.info("[ObservableExample] name-service result: {}", userName); - hashService.register(RxObservableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the hash value for + getHashService().register(RxObservableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxObservableInvoker.class).get(String.class).asObservable() // gotten the hash value for // userId+username .doOnError((throwable) -> { logger.warn("[ObservableExample] An error has occurred in the hashing request step {}", throwable.getMessage()); @@ -233,18 +233,18 @@ public class ClientOrchestrationIntegrationTest { final CountDownLatch completionTracker = new CountDownLatch(expectedHashValues.size()); // used to keep track of the progress of the subsequent calls - Flowable> userIdFlowable = userIdService.register(RxFlowableInvokerProvider.class).request().rx(RxFlowableInvoker.class).get(new GenericType>() { + Flowable> userIdFlowable = getUserIdService().register(RxFlowableInvokerProvider.class).request().rx(RxFlowableInvoker.class).get(new GenericType>() { }); userIdFlowable.subscribe((List employeeIds) -> { logger.info("[FlowableExample] id-service result: {}", employeeIds); Flowable.fromIterable(employeeIds).subscribe(id -> { - nameService.register(RxFlowableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the name for the given userId + getNameService().register(RxFlowableInvokerProvider.class).resolveTemplate("userId", id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the name for the given userId .doOnError((throwable) -> { logger.warn("[FlowableExample] An error has occurred in the username request step {}", throwable.getMessage()); }).subscribe(userName -> { logger.info("[FlowableExample] name-service result: {}", userName); - hashService.register(RxFlowableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the hash value for userId+username + getHashService().register(RxFlowableInvokerProvider.class).resolveTemplate("rawValue", userName + id).request().rx(RxFlowableInvoker.class).get(String.class) // gotten the hash value for userId+username .doOnError((throwable) -> { logger.warn(" [FlowableExample] An error has occurred in the hashing request step!", throwable); }).subscribe(hashValue -> { @@ -269,4 +269,20 @@ public class ClientOrchestrationIntegrationTest { assertThat(receivedHashValues).containsAll(expectedHashValues); } + private int getPort() { + return wireMockServer.port(); + } + + private WebTarget getUserIdService() { + return userIdService.resolveTemplate("port", getPort()); + } + + private WebTarget getNameService() { + return nameService.resolveTemplate("port", getPort()); + } + + private WebTarget getHashService() { + return hashService.resolveTemplate("port", getPort()); + } + } diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index f142b3ee2f..1661614fa0 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -9,8 +9,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-1 + 0.0.1-SNAPSHOT @@ -59,20 +59,7 @@ - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - 1.5.9.RELEASE 1.8.22 diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceUnitTest.java similarity index 95% rename from spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java rename to spring-mockito/src/test/java/com/baeldung/UserServiceUnitTest.java index 573a37a9a4..11c7b4d8a8 100644 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceUnitTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = MocksApplication.class) -public class UserServiceIntegrationUnitTest { +public class UserServiceUnitTest { @Autowired private UserService userService; diff --git a/spring-mvc-simple-2/README.md b/spring-mvc-simple-2/README.md index c03fa6363a..cff8891a1a 100644 --- a/spring-mvc-simple-2/README.md +++ b/spring-mvc-simple-2/README.md @@ -6,4 +6,8 @@ This module contains articles about Spring MVC - [How to Read HTTP Headers in Spring REST Controllers](https://www.baeldung.com/spring-rest-http-headers) - [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder) - [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) +- [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation) +- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url) +- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param) +- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) - More articles: [[<-- prev]](/spring-mvc-simple) diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/Application.java b/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/Application.java new file mode 100644 index 0000000000..0472ba4e7b --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.flash_attributes; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/controllers/PoemSubmission.java b/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/controllers/PoemSubmission.java new file mode 100644 index 0000000000..6264ea0531 --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/controllers/PoemSubmission.java @@ -0,0 +1,49 @@ +package com.baeldung.flash_attributes.controllers; + +import com.baeldung.flash_attributes.model.Poem; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; +import org.springframework.web.servlet.support.RequestContextUtils; +import org.springframework.web.servlet.view.RedirectView; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +@Controller +public class PoemSubmission { + + @GetMapping("/poem/success") + public String getSuccess(HttpServletRequest request) { + Map inputFlashMap = RequestContextUtils.getInputFlashMap(request); + if (inputFlashMap != null) { + Poem poem = (Poem) inputFlashMap.get("poem"); + return "success"; + } else { + return "redirect:/poem/submit"; + } + } + + @PostMapping("/poem/submit") + public RedirectView submitPost( + HttpServletRequest request, + @ModelAttribute Poem poem, + RedirectAttributes redirectAttributes) { + if (Poem.isValidPoem(poem)) { + redirectAttributes.addFlashAttribute("poem", poem); + return new RedirectView("/poem/success", true); + } else { + return new RedirectView("/poem/submit", true); + } + } + + @GetMapping("/poem/submit") + public String submitGet(Model model) { + model.addAttribute("poem", new Poem()); + return "submit"; + } + +} \ No newline at end of file diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/model/Poem.java b/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/model/Poem.java new file mode 100644 index 0000000000..bff65456c1 --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/flash_attributes/model/Poem.java @@ -0,0 +1,39 @@ +package com.baeldung.flash_attributes.model; + +import org.apache.logging.log4j.util.Strings; + +public class Poem { + private String title; + private String author; + private String body; + + public static boolean isValidPoem(Poem poem) { + return poem != null && Strings.isNotBlank(poem.getAuthor()) && Strings.isNotBlank(poem.getBody()) + && Strings.isNotBlank(poem.getTitle()); + } + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return this.body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getAuthor() { + return this.author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/spring-mvc-simple-2/src/main/resources/application.properties b/spring-mvc-simple-2/src/main/resources/application.properties index 709574239b..aca20f4e3c 100644 --- a/spring-mvc-simple-2/src/main/resources/application.properties +++ b/spring-mvc-simple-2/src/main/resources/application.properties @@ -1 +1,9 @@ -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true + +spring.mail.host=localhost +spring.mail.port=8025 + +spring.thymeleaf.cache=false +spring.thymeleaf.enabled=true +spring.thymeleaf.prefix=classpath:/templates/ +spring.thymeleaf.suffix=.html diff --git a/spring-mvc-simple-2/src/main/resources/templates/submit.html b/spring-mvc-simple-2/src/main/resources/templates/submit.html new file mode 100644 index 0000000000..0ed0107c20 --- /dev/null +++ b/spring-mvc-simple-2/src/main/resources/templates/submit.html @@ -0,0 +1,50 @@ + + + + Poetry Contest: Submission + + + +
+ + + + + + + + + + + + + + + +
+ + + +
+ + + +
+ + +