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/akka-http/README.md b/akka-http/README.md index 3831b5079f..ebe6581ff6 100644 --- a/akka-http/README.md +++ b/akka-http/README.md @@ -1,3 +1,7 @@ -## Relevant articles: +## Akka HTTP + +This module contains articles about Akka HTTP. + +### Relevant articles: - [Introduction to Akka HTTP](https://www.baeldung.com/akka-http) diff --git a/akka-streams/README.md b/akka-streams/README.md index 5f71991def..a59b7fde5c 100644 --- a/akka-streams/README.md +++ b/akka-streams/README.md @@ -1,3 +1,7 @@ +## Akka Streams + +This module contains articles about Akka Streams. + ### Relevant articles - [Guide to Akka Streams](https://www.baeldung.com/akka-streams) diff --git a/algorithms-genetic/README.md b/algorithms-genetic/README.md index 124e9c09e5..1c9e831ac2 100644 --- a/algorithms-genetic/README.md +++ b/algorithms-genetic/README.md @@ -1,4 +1,8 @@ -## Relevant articles: +## Genetic Algorithms + +This module contains articles about genetic algorithms. + +### Relevant articles: - [Introduction to Jenetics Library](https://www.baeldung.com/jenetics) - [Ant Colony Optimization](https://www.baeldung.com/java-ant-colony-optimization) diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md index 57f5a5d478..6a25f8cac8 100644 --- a/algorithms-miscellaneous-1/README.md +++ b/algorithms-miscellaneous-1/README.md @@ -1,4 +1,9 @@ -## Relevant articles: +## 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. + +### Relevant articles: - [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata) - [Example of Hill Climbing Algorithm](https://www.baeldung.com/java-hill-climbing-algorithm) @@ -6,4 +11,5 @@ - [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search) - [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm) - [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance) -- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element) \ No newline at end of file +- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element) +- More articles: [[next -->]](/../algorithms-miscellaneous-2) diff --git a/algorithms-miscellaneous-2/README.md b/algorithms-miscellaneous-2/README.md index 76727a1d4f..7560fc4fe7 100644 --- a/algorithms-miscellaneous-2/README.md +++ b/algorithms-miscellaneous-2/README.md @@ -1,4 +1,9 @@ -## Relevant articles: +## 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. + +### Relevant articles: - [Dijkstra Shortest Path Algorithm in Java](https://www.baeldung.com/java-dijkstra) - [Introduction to Cobertura](https://www.baeldung.com/cobertura) @@ -8,3 +13,4 @@ - [Create a Sudoku Solver in Java](https://www.baeldung.com/java-sudoku) - [Displaying Money Amounts in Words](https://www.baeldung.com/java-money-into-words) - [A Collaborative Filtering Recommendation System in Java](https://www.baeldung.com/java-collaborative-filtering-recommendations) +- More articles: [[<-- prev]](/../algorithms-miscellaneous-1) [[next -->]](/../algorithms-miscellaneous-3) 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 fabb4d29b8..df2eafb733 100644 --- a/algorithms-miscellaneous-4/README.md +++ b/algorithms-miscellaneous-4/README.md @@ -1,4 +1,8 @@ -## Relevant articles: +## Algorithms - Miscellaneous + +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: - [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm) - [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms) @@ -6,4 +10,5 @@ - [Find the Middle Element of a Linked List](https://www.baeldung.com/java-linked-list-middle-element) - [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) \ No newline at end of file +- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations) +- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5) diff --git a/algorithms-miscellaneous-5/README.md b/algorithms-miscellaneous-5/README.md index 7ed71e61cc..7a8f2e0a36 100644 --- a/algorithms-miscellaneous-5/README.md +++ b/algorithms-miscellaneous-5/README.md @@ -1,5 +1,11 @@ -## Relevant articles: +## 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. + +### Relevant articles: - [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) \ No newline at end of file +- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers) +- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java new file mode 100644 index 0000000000..61c3f05a95 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/knapsack/Knapsack.java @@ -0,0 +1,36 @@ +package com.baeldung.algorithms.knapsack; + +public class Knapsack { + + public int knapsackRec(int[] w, int[] v, int n, int W) { + if (n <= 0) { + return 0; + } else if (w[n - 1] > W) { + return knapsackRec(w, v, n - 1, W); + } else { + return Math.max(knapsackRec(w, v, n - 1, W), v[n - 1] + knapsackRec(w, v, n - 1, W - w[n - 1])); + } + } + + public int knapsackDP(int[] w, int[] v, int n, int W) { + if (n <= 0 || W <= 0) { + return 0; + } + + int[][] m = new int[n + 1][W + 1]; + for (int j = 0; j <= W; j++) { + m[0][j] = 0; + } + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= W; j++) { + if (w[i - 1] > j) { + m[i][j] = m[i - 1][j]; + } else { + m[i][j] = Math.max(m[i - 1][j], m[i - 1][j - w[i - 1]] + v[i - 1]); + } + } + } + return m[n][W]; + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java new file mode 100644 index 0000000000..b168e6b1eb --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.algorithms.knapsack; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class KnapsackUnitTest { + + @Test + public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() { + final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; + final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; + final int n = 10; + final int W = 67; + final Knapsack knapsack = new Knapsack(); + + assertEquals(1270, knapsack.knapsackRec(w, v, n, W)); + assertEquals(1270, knapsack.knapsackDP(w, v, n, W)); + } + + @Test + public void givenZeroItems_whenCalculateMax_thenOutputZero() { + final int[] w = new int[] {}; + final int[] v = new int[] {}; + final int n = 0; + final int W = 67; + final Knapsack knapsack = new Knapsack(); + + assertEquals(0, knapsack.knapsackRec(w, v, n, W)); + assertEquals(0, knapsack.knapsackDP(w, v, n, W)); + } + + @Test + public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() { + final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; + final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; + final int n = 10; + final int W = 0; + final Knapsack knapsack = new Knapsack(); + + assertEquals(0, knapsack.knapsackRec(w, v, n, W)); + assertEquals(0, knapsack.knapsackDP(w, v, n, W)); + } +} diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md index 4fd9d5e0c6..15a5ec6e02 100644 --- a/algorithms-sorting/README.md +++ b/algorithms-sorting/README.md @@ -16,3 +16,5 @@ This module contains articles about sorting algorithms. - [Selection Sort in Java](https://www.baeldung.com/java-selection-sort) - [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) - [Radix Sort in Java](https://www.baeldung.com/java-radix-sort) +- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort) diff --git a/algorithms-sorting/pom.xml b/algorithms-sorting/pom.xml index b25adf05a8..5bb19a8069 100644 --- a/algorithms-sorting/pom.xml +++ b/algorithms-sorting/pom.xml @@ -28,6 +28,12 @@ ${lombok.version} provided + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter-api.version} + test + org.assertj assertj-core @@ -52,6 +58,7 @@ 3.6.1 3.9.0 1.11 + 5.3.1 \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java similarity index 93% rename from java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java index c4f684383d..67b5e5facc 100644 --- a/java-strings/src/main/java/com/baeldung/string/sorting/AnagramValidator.java +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java @@ -1,4 +1,4 @@ -package com.baeldung.string.sorting; +package com.baeldung.algorithms.stringsort; import java.util.Arrays; diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java similarity index 86% rename from java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java index 07d31c7187..25fc274dd8 100644 --- a/java-strings/src/test/java/com/baeldung/string/sorting/AnagramValidatorUnitTest.java +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java @@ -1,12 +1,10 @@ -package com.baeldung.string.sorting; +package com.baeldung.algorithms.stringsort; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; - import org.junit.jupiter.api.Test; -import com.baeldung.string.sorting.AnagramValidator; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; class AnagramValidatorUnitTest { diff --git a/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java similarity index 94% rename from java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java index 90d1dad554..226de64f07 100644 --- a/java-strings/src/test/java/com/baeldung/string/sorting/SortStringUnitTest.java +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.sorting; - -import java.util.Arrays; +package com.baeldung.algorithms.stringsort; import org.junit.jupiter.api.Test; +import java.util.Arrays; + import static org.assertj.core.api.Assertions.assertThat; class SortStringUnitTest { 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/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java index 7a9f62341e..82a84bb2d6 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java @@ -1,12 +1,12 @@ package com.baeldung.java_8_features.groupingby; -public class Tuple { +import java.util.Objects; + +public class Tuple { + private final BlogPostType type; + private final String author; - private BlogPostType type; - private String author; - public Tuple(BlogPostType type, String author) { - super(); this.type = type; this.author = author; } @@ -15,20 +15,27 @@ public class Tuple { return type; } - public void setType(BlogPostType type) { - this.type = type; - } - public String getAuthor() { return author; } - public void setAuthor(String author) { - this.author = author; + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Tuple tuple = (Tuple) o; + return type == tuple.type && author.equals(tuple.author); + } + + @Override + public int hashCode() { + return Objects.hash(type, author); } @Override public String toString() { - return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; + return "Tuple{" + "type=" + type + ", author='" + author + '\'' + '}'; } } diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java index 323586b85f..1da705294e 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java @@ -1,15 +1,32 @@ package com.baeldung.java_8_features.groupingby; -import com.baeldung.java_8_features.groupingby.BlogPost; -import com.baeldung.java_8_features.groupingby.BlogPostType; -import org.junit.Test; +import static java.util.Comparator.comparingInt; +import static java.util.stream.Collectors.averagingInt; +import static java.util.stream.Collectors.counting; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.groupingByConcurrent; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.mapping; +import static java.util.stream.Collectors.maxBy; +import static java.util.stream.Collectors.summarizingInt; +import static java.util.stream.Collectors.summingInt; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; -import java.util.*; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.IntSummaryStatistics; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentMap; -import static java.util.Comparator.comparingInt; -import static java.util.stream.Collectors.*; -import static org.junit.Assert.*; +import org.junit.Test; public class Java8GroupingByCollectorUnitTest { @@ -180,4 +197,19 @@ public class Java8GroupingByCollectorUnitTest { assertEquals(15, newsLikeStatistics.getMin()); } + @Test + public void givenAListOfPosts_whenGroupedByComplexMapKeyType_thenGetAMapBetweenTupleAndList() { + Map> postsPerTypeAndAuthor = posts.stream() + .collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor()))); + + List result = postsPerTypeAndAuthor.get(new Tuple(BlogPostType.GUIDE, "Author 1")); + + assertThat(result.size()).isEqualTo(1); + + BlogPost blogPost = result.get(0); + + assertThat(blogPost.getTitle()).isEqualTo("Programming guide"); + assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE); + assertThat(blogPost.getAuthor()).isEqualTo("Author 1"); + } } 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-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/src/main/java/com/baeldung/array/operations/ArrayOperations.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java index 94a00f7aba..4513dbf899 100644 --- a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java +++ b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/operations/ArrayOperations.java @@ -192,15 +192,48 @@ public class ArrayOperations { return array[new Random().nextInt(array.length)]; } - public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b){ - return Stream.of(a).filter(Arrays.asList(b)::contains).toArray(Integer[]::new); + public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(Arrays.asList(b)::contains) + .toArray(Integer[]::new); } - public static Integer[] intersectionSet(final Integer[] a, final Integer[] b){ - return Stream.of(a).filter(Arrays.asList(b)::contains).distinct().toArray(Integer[]::new); + public static Integer[] intersectionSet(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(Arrays.asList(b)::contains) + .distinct() + .toArray(Integer[]::new); } - public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b){ - return Stream.of(a).filter(new LinkedList<>(Arrays.asList(b))::remove).toArray(Integer[]::new); + public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b) { + return Stream.of(a) + .filter(new LinkedList<>(Arrays.asList(b))::remove) + .toArray(Integer[]::new); + } + + public static Integer[] addElementUsingPureJava(Integer[] srcArray, int elementToAdd) { + Integer[] destArray = new Integer[srcArray.length + 1]; + + for (int i = 0; i < srcArray.length; i++) { + destArray[i] = srcArray[i]; + } + + destArray[destArray.length - 1] = elementToAdd; + return destArray; + } + + public static int[] insertAnElementAtAGivenIndex(final int[] srcArray, int index, int newElement) { + int[] destArray = new int[srcArray.length + 1]; + int j = 0; + for (int i = 0; i < destArray.length - 1; i++) { + + if (i == index) { + destArray[i] = newElement; + } else { + destArray[i] = srcArray[j]; + j++; + } + } + return destArray; } } diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java new file mode 100644 index 0000000000..b2aed553da --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraylist/operations/ArrayListOperations.java @@ -0,0 +1,23 @@ +package com.baeldung.arraylist.operations; + +import java.util.ArrayList; + +public class ArrayListOperations { + + public static Integer getAnIntegerElement(ArrayList anArrayList, int index) { + return anArrayList.get(index); + } + + public static void modifyAnIntegerElement(ArrayList anArrayList, int index, Integer newElement) { + anArrayList.set(index, newElement); + } + + public static void appendAnIntegerElement(ArrayList anArrayList, Integer newElement) { + anArrayList.add(newElement); + } + + public static void insertAnIntegerElementAtIndex(ArrayList anArrayList, int index, Integer newElement) { + anArrayList.add(index, newElement); + } + +} diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java index d72681ca05..ea9bf2c5a9 100644 --- a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java +++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/operations/ArrayOperationsUnitTest.java @@ -1,12 +1,11 @@ package com.baeldung.array.operations; +import java.util.Arrays; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - -import java.util.Arrays; - import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertArrayEquals; public class ArrayOperationsUnitTest { @@ -262,8 +261,7 @@ public class ArrayOperationsUnitTest { @Test public void whenMapIntArrayToString_thenReturnArray() { - String[] expectedArray = new String[] { "Value: 3", "Value: 5", "Value: 2", "Value: 5", "Value: 14", - "Value: 4" }; + String[] expectedArray = new String[] { "Value: 3", "Value: 5", "Value: 2", "Value: 5", "Value: 14", "Value: 4" }; String[] output = ArrayOperations.mapIntArrayToString(defaultIntArray); assertThat(output).containsExactly(expectedArray); @@ -313,13 +311,10 @@ public class ArrayOperationsUnitTest { int[] output5 = ArrayOperations.shuffleIntArray(defaultIntArray); int[] output6 = ArrayOperations.shuffleIntArray(defaultIntArray); - Condition atLeastOneArraysIsNotEqual = new Condition( - "at least one output should be different (order-wise)") { + Condition atLeastOneArraysIsNotEqual = new Condition("at least one output should be different (order-wise)") { @Override public boolean matches(int[] value) { - return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) - || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) - || !Arrays.equals(value, output6); + return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6); } }; @@ -335,13 +330,10 @@ public class ArrayOperationsUnitTest { Integer[] output5 = ArrayOperations.shuffleObjectArray(defaultObjectArray); Integer[] output6 = ArrayOperations.shuffleObjectArray(defaultObjectArray); - Condition atLeastOneArraysIsNotEqual = new Condition( - "at least one output should be different (order-wise)") { + Condition atLeastOneArraysIsNotEqual = new Condition("at least one output should be different (order-wise)") { @Override public boolean matches(Integer[] value) { - return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) - || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) - || !Arrays.equals(value, output6); + return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6); } }; @@ -362,4 +354,27 @@ public class ArrayOperationsUnitTest { assertThat(defaultObjectArray).contains(output); } + + @Test + public void givenSourceArrayAndElement_whenAddElementUsingPureJavaIsInvoked_thenNewElementMustBeAdded() { + Integer[] sourceArray = { 1, 2, 3, 4 }; + int elementToAdd = 5; + + Integer[] destArray = ArrayOperations.addElementUsingPureJava(sourceArray, elementToAdd); + + Integer[] expectedArray = { 1, 2, 3, 4, 5 }; + assertArrayEquals(expectedArray, destArray); + } + + @Test + public void whenInsertAnElementAtAGivenIndexCalled_thenShiftTheFollowingElementsAndInsertTheElementInArray() { + int[] expectedArray = { 1, 4, 2, 3, 0 }; + int[] anArray = new int[4]; + anArray[0] = 1; + anArray[1] = 2; + anArray[2] = 3; + int[] outputArray = ArrayOperations.insertAnElementAtAGivenIndex(anArray, 1, 4); + + assertThat(outputArray).containsExactly(expectedArray); + } } diff --git a/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java new file mode 100644 index 0000000000..1ec7645d8f --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/arraylist/operations/ArrayListOperationsUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.arraylist.operations; + +import java.util.ArrayList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class ArrayListOperationsUnitTest { + + private ArrayList anArrayList; + + @BeforeEach + public void setupDefaults() { + anArrayList = new ArrayList<>(); + anArrayList.add(2); + anArrayList.add(3); + anArrayList.add(4); + } + + @Test + public void whenGetAnIntegerElementCalled_thenReturnTheIntegerElement() { + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 1); + + assertThat(output).isEqualTo(3); + } + + @Test + public void whenModifyAnIntegerElementCalled_thenModifyTheIntegerElement() { + ArrayListOperations.modifyAnIntegerElement(anArrayList, 2, 5); + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 2); + + assertThat(output).isEqualTo(5); + } + + @Test + public void whenAppendAnIntegerElementCalled_thenTheIntegerElementIsAppendedToArrayList() { + ArrayListOperations.appendAnIntegerElement(anArrayList, 6); + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, anArrayList.size() - 1); + + assertThat(output).isEqualTo(6); + } + + @Test + public void whenInsertAnIntegerAtIndexCalled_thenTheIntegerElementIsInseredToArrayList() { + ArrayListOperations.insertAnIntegerElementAtIndex(anArrayList, 1, 10); + Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 1); + + assertThat(output).isEqualTo(10); + } +} \ No newline at end of file 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-collections-list-3/src/main/java/com/baeldung/list/DuplicatesCounter.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/DuplicatesCounter.java new file mode 100644 index 0000000000..04e24e5fa1 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/DuplicatesCounter.java @@ -0,0 +1,42 @@ +package com.baeldung.list; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Demo different approaches to get count of duplicated elements in an + * arrayList + */ +public class DuplicatesCounter { + + public static Map countByClassicalLoop(List inputList) { + Map resultMap = new HashMap<>(); + for (T element : inputList) { + if (resultMap.containsKey(element)) { + resultMap.put(element, resultMap.get(element) + 1L); + } else { + resultMap.put(element, 1L); + } + } + return resultMap; + } + + public static Map countByClassicalLoopWithMapCompute(List inputList) { + Map resultMap = new HashMap<>(); + for (T element : inputList) { + resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1); + } + return resultMap; + } + + public static Map countByStreamToMap(List inputList) { + return inputList.stream().collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum)); + } + + public static Map countByStreamGroupBy(List inputList) { + return inputList.stream().collect(Collectors.groupingBy(k -> k, Collectors.counting())); + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/DuplicatesCounterUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/DuplicatesCounterUnitTest.java new file mode 100644 index 0000000000..4b6a03aaef --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/list/DuplicatesCounterUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.list; + +import org.assertj.core.util.Lists; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.MapEntry.entry; + +class DuplicatesCounterUnitTest { + + + private static List INPUT_LIST = Lists.list( + "expect1", + "expect2", "expect2", + "expect3", "expect3", "expect3", + "expect4", "expect4", "expect4", "expect4"); + + @Test + void givenInput_whenCountByClassicalLoop_thenGetResultMap() { + Map result = DuplicatesCounter.countByClassicalLoop(INPUT_LIST); + verifyResult(result); + } + + + @Test + void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() { + Map result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByStreamToMap_thenGetResultMap() { + Map result = DuplicatesCounter.countByStreamToMap(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByStreamGroupBy_thenGetResultMap() { + Map result = DuplicatesCounter.countByStreamGroupBy(INPUT_LIST); + verifyResult(result); + } + + private void verifyResult(Map resultMap) { + assertThat(resultMap) + .isNotEmpty().hasSize(4) + .containsExactly( + entry("expect1", 1L), + entry("expect2", 2L), + entry("expect3", 3L), + entry("expect4", 4L)); + } +} \ 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/java-dates-2/pom.xml b/core-java-modules/core-java-datetime-computations/pom.xml similarity index 76% rename from java-dates-2/pom.xml rename to core-java-modules/core-java-datetime-computations/pom.xml index 08b2076d03..934df8018f 100644 --- a/java-dates-2/pom.xml +++ b/core-java-modules/core-java-datetime-computations/pom.xml @@ -1,17 +1,16 @@ 4.0.0 - com.baeldung - java-dates-2 - 0.1.0-SNAPSHOT + core-java-datetime-computations + ${project.parent.version} + core-java-datetime-computations jar - java-dates-2 com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java @@ -20,31 +19,28 @@ joda-time ${joda-time.version}
- org.apache.commons commons-lang3 ${commons-lang3.version} - - - commons-validator - commons-validator - ${commons-validator.version} - - - org.assertj assertj-core ${assertj.version} test + + com.darwinsys + hirondelle-date4j + RELEASE + test + - java-dates-2 + core-java-datetime-computations src/main/resources @@ -66,11 +62,9 @@ + 2.10 3.6.1 - 2.10 - 3.9 - 1.6 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 97% 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 index a35699e469..226556d4bb 100644 --- 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 @@ -1,6 +1,6 @@ package com.baeldung.date; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -16,7 +16,7 @@ import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; +import org.junit.Test; public class DateDiffUnitTest { @@ -31,14 +31,14 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } - + @Test public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() { LocalDate now = LocalDate.now(); LocalDate sixDaysBehind = now.minusDays(6); Period period = Period.between(now, sixDaysBehind); - int diff = period.getDays(); + int diff = Math.abs(period.getDays()); assertEquals(diff, 6); } @@ -68,7 +68,8 @@ public class DateDiffUnitTest { public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() { LocalDateTime ldt = LocalDateTime.now(); ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal")); - ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6); + ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")) + .minusDays(6); long diff = ChronoUnit.DAYS.between(sixDaysBehind, now); assertEquals(diff, 6); } 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-conversion/README.md b/core-java-modules/core-java-datetime-conversion/README.md new file mode 100644 index 0000000000..2503459f50 --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/README.md @@ -0,0 +1,9 @@ +## Java Date/time conversion Cookbooks and Examples + +This module contains articles about converting between Java date and time objects. + +### Relevant Articles: +- [Converting Between LocalDate and XMLGregorianCalendar](https://www.baeldung.com/java-localdate-to-xmlgregoriancalendar) +- [Convert Time to Milliseconds in Java](https://www.baeldung.com/java-time-milliseconds) +- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime) +- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp) diff --git a/core-java-modules/core-java-datetime-conversion/pom.xml b/core-java-modules/core-java-datetime-conversion/pom.xml new file mode 100644 index 0000000000..a93eca00af --- /dev/null +++ b/core-java-modules/core-java-datetime-conversion/pom.xml @@ -0,0 +1,70 @@ + + 4.0.0 + core-java-datetime-conversion + ${project.parent.version} + core-java-datetime-conversion + 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} + + + log4j + log4j + ${log4j.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-datetime-conversion + + + 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/datetolocaldate/DateToLocalDateConverter.java b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateConverter.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateConverter.java rename to core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateConverter.java diff --git a/java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverter.java b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverter.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverter.java rename to core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverter.java diff --git a/java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverter.java b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverter.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverter.java rename to core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverter.java diff --git a/java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateToDateConverter.java b/core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/LocalDateToDateConverter.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateToDateConverter.java rename to core-java-modules/core-java-datetime-conversion/src/main/java/com/baeldung/datetolocaldate/LocalDateToDateConverter.java diff --git a/java-dates-2/src/test/java/com/baeldung/convert/ConvertDateTimeUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/convert/ConvertDateTimeUnitTest.java similarity index 100% rename from java-dates-2/src/test/java/com/baeldung/convert/ConvertDateTimeUnitTest.java rename to core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/convert/ConvertDateTimeUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java similarity index 97% rename from java-dates/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java rename to core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java index 3ba01a591a..e5fd80285c 100644 --- a/java-dates/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java +++ b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.datetime; -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Instant; -import java.time.ZoneId; import java.util.TimeZone; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; public class ConvertInstantToTimestampUnitTest { diff --git a/java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateConverterUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateConverterUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateConverterUnitTest.java rename to core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateConverterUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverterUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverterUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverterUnitTest.java rename to core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverterUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverterUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverterUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverterUnitTest.java rename to core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverterUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateToDateConverterUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/LocalDateToDateConverterUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateToDateConverterUnitTest.java rename to core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/datetolocaldate/LocalDateToDateConverterUnitTest.java diff --git a/java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java b/core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java similarity index 100% rename from java-dates-2/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.java rename to core-java-modules/core-java-datetime-conversion/src/test/java/com/baeldung/xmlgregoriancalendar/XmlGregorianCalendarConverterUnitTest.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/core-java-modules/core-java-datetime-java8/pom.xml b/core-java-modules/core-java-datetime-java8/pom.xml new file mode 100644 index 0000000000..72d51b5f10 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/pom.xml @@ -0,0 +1,70 @@ + + 4.0.0 + core-java-datetime-java8 + ${project.parent.version} + core-java-datetime-java8 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + joda-time + joda-time + ${joda-time.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + log4j + log4j + ${log4j.version} + test + + + + + core-java-datetime-java8 + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 1.9 + 1.9 + 2.10 + + 3.6.1 + + diff --git a/java-dates-2/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-2/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-2/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-2/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 91% 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 index b380c04fc2..ec8dfa2fc4 100644 --- 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 @@ -36,10 +36,15 @@ class UseLocalDate { } LocalDate getFirstDayOfMonth() { - LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); + LocalDate firstDayOfMonth = LocalDate.now() + .with(TemporalAdjusters.firstDayOfMonth()); return firstDayOfMonth; } + boolean isLeapYear(LocalDate localDate) { + return localDate.isLeapYear(); + } + LocalDateTime getStartOfDay(LocalDate localDate) { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; 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 80% 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 index b2ff11ba16..267a9412eb 100644 --- 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 @@ -2,6 +2,7 @@ package com.baeldung.datetime; import java.time.LocalDateTime; import java.time.LocalTime; +import java.time.ZoneOffset; import java.time.temporal.ChronoField; public class UseLocalDateTime { @@ -21,4 +22,7 @@ public class UseLocalDateTime { return endOfDate; } + LocalDateTime ofEpochSecond(int epochSecond, ZoneOffset zoneOffset) { + return LocalDateTime.ofEpochSecond(epochSecond, 0, zoneOffset); + } } 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 87% 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 index 8d166c413f..876516e365 100644 --- 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 @@ -9,6 +9,10 @@ public class UseLocalTime { return LocalTime.of(hour, min, seconds); } + LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min) { + return LocalTime.of(hour, min); + } + LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) { return LocalTime.parse(timeRepresentation); } 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 61% 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 index 505bfa741f..a8948e5ce1 100644 --- 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 @@ -12,31 +12,35 @@ class UseZonedDateTime { return ZonedDateTime.of(localDateTime, zoneId); } + ZonedDateTime getZonedDateTimeUsingParseMethod(String parsableString) { + return ZonedDateTime.parse(parsableString); + } + ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) { - ZonedDateTime startofDay = localDate.atStartOfDay() + ZonedDateTime startOfDay = localDate.atStartOfDay() .atZone(zone); - return startofDay; + return startOfDay; } ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) { - ZonedDateTime startofDay = localDate.atStartOfDay(zone); - return startofDay; + ZonedDateTime startOfDay = localDate.atStartOfDay(zone); + return startOfDay; } ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) { - ZonedDateTime startofDay = zonedDateTime.toLocalDateTime() + ZonedDateTime startOfDay = zonedDateTime.toLocalDateTime() .toLocalDate() .atStartOfDay(zonedDateTime.getZone()); - return startofDay; + return startOfDay; } ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) { - ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0); - return startofDay; + ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0); + return startOfDay; } ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) { - ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0); - return startofDay; + ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0); + return startOfDay; } } 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-2/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-2/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-2/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 85% rename from java-dates-2/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 index ff51476e7c..af72f9e58a 100644 --- a/java-dates-2/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 @@ -1,12 +1,16 @@ package com.baeldung.date.comparison; -import org.junit.Test; - -import java.time.*; - import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; + public class Java8DateTimeApiGeneralComparisonsUnitTest { @Test @@ -54,10 +58,8 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest { @Test public void givenZonedDateTimes_whenComparing_thenAssertsPass() { - ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0, - ZoneId.of("America/New_York")); - ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0, - ZoneId.of("Europe/Berlin")); + ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0, ZoneId.of("America/New_York")); + ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0, ZoneId.of("Europe/Berlin")); assertThat(timeInNewYork.isAfter(timeInBerlin), is(false)); assertThat(timeInNewYork.isBefore(timeInBerlin), is(false)); @@ -80,4 +82,14 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest { assertThat(firstTime.compareTo(secondTime), is(-1)); } + + @Test + public void givenMinMaxLocalTimes_whenComparing_thenAssertsPass() { + LocalTime minTime = LocalTime.MIN; + LocalTime time = LocalTime.of(8, 30); + LocalTime maxTime = LocalTime.MAX; + + assertThat(minTime.isBefore(time), is(true)); + assertThat(time.isBefore(maxTime), is(true)); + } } \ No newline at end of file diff --git a/java-dates-2/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-2/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/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java new file mode 100644 index 0000000000..be43fb609a --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.dateapi; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.time.Duration; +import java.time.Instant; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; + +import org.junit.Test; + +public class JavaDurationUnitTest { + + @Test + public void givenATimePlus30Seconds_whenRequestingDuration_thenExpect30() { + LocalTime initialTime = LocalTime.of(6, 30, 0); + LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30)); + + long seconds = Duration.between(initialTime, finalTime) + .getSeconds(); + + assertThat(seconds).isEqualTo(30); + } + + @Test + public void givenATimePlus30Seconds_whenRequestingSecondsBetween_thenExpect30() { + LocalTime initialTime = LocalTime.of(6, 30, 0); + LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30)); + + long seconds = ChronoUnit.SECONDS.between(initialTime, finalTime); + + assertThat(seconds).isEqualTo(30); + } + + @Test + public void test2() { + Instant start = Instant.parse("2017-10-03T10:15:30.00Z"); + Instant end = Instant.parse("2017-10-03T10:16:30.00Z"); + + Duration duration = Duration.between(start, end); + + assertFalse(duration.isNegative()); + + assertEquals(60, duration.getSeconds()); + assertEquals(1, duration.toMinutes()); + + Duration fromDays = Duration.ofDays(1); + assertEquals(86400, fromDays.getSeconds()); + + Duration fromMinutes = Duration.ofMinutes(60); + assertEquals(1, fromMinutes.toHours()); + + assertEquals(120, duration.plusSeconds(60) + .getSeconds()); + assertEquals(30, duration.minusSeconds(30) + .getSeconds()); + + assertEquals(120, duration.plus(60, ChronoUnit.SECONDS) + .getSeconds()); + assertEquals(30, duration.minus(30, ChronoUnit.SECONDS) + .getSeconds()); + + Duration fromChar1 = Duration.parse("P1DT1H10M10.5S"); + Duration fromChar2 = Duration.parse("PT10M"); + } + +} 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 57% 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 index 81e9153a51..6dfbbe8c24 100644 --- 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 @@ -1,18 +1,41 @@ package com.baeldung.dateapi; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.ChronoUnit; + import org.apache.log4j.Logger; import org.junit.Test; -import java.time.LocalDate; -import java.time.Period; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - public class JavaPeriodUnitTest { private static final Logger LOG = Logger.getLogger(JavaPeriodUnitTest.class); + @Test + public void givenADatePlus5Days_whenRequestingPeriod_thenExpectFive() { + LocalDate initialDate = LocalDate.parse("2007-05-10"); + LocalDate finalDate = initialDate.plus(Period.ofDays(5)); + + int days = Period.between(initialDate, finalDate) + .getDays(); + + assertThat(days).isEqualTo(5); + } + + @Test + public void givenADatePlus5Days_whenRequestingDaysBetween_thenExpectFive() { + LocalDate initialDate = LocalDate.parse("2007-05-10"); + LocalDate finalDate = initialDate.plus(Period.ofDays(5)); + + long days = ChronoUnit.DAYS.between(initialDate, finalDate); + + assertThat(days).isEqualTo(5); + } + @Test public void whenTestPeriod_thenOk() { @@ -24,8 +47,10 @@ public class JavaPeriodUnitTest { LOG.info(String.format("Years:%d months:%d days:%d", period.getYears(), period.getMonths(), period.getDays())); assertFalse(period.isNegative()); - assertEquals(56, period.plusDays(50).getDays()); - assertEquals(9, period.minusMonths(2).getMonths()); + assertEquals(56, period.plusDays(50) + .getDays()); + assertEquals(9, period.minusMonths(2) + .getMonths()); Period fromUnits = Period.of(3, 10, 10); Period fromDays = Period.ofDays(50); 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 55% 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 index 5709fc7209..2bbee16e25 100644 --- 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 @@ -7,12 +7,13 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; +import java.time.ZoneOffset; import org.junit.Test; public class UseLocalDateTimeUnitTest { - UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); + private UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); @Test public void givenString_whenUsingParse_thenLocalDateTime() { @@ -33,4 +34,28 @@ public class UseLocalDateTimeUnitTest { assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX); assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); } + + @Test + public void givenLocalDateTimeInFebruary_whenRequestingMonth_thenMonthIsFebruary() { + LocalDateTime givenLocalDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 6, 30); + + assertThat(givenLocalDateTime.getMonth()).isEqualTo(Month.FEBRUARY); + } + + @Test + public void givenLocalDateTime_whenManipulating_thenResultIsAsExpected() { + LocalDateTime givenLocalDateTime = LocalDateTime.parse("2015-02-20T06:30:00"); + + LocalDateTime manipulatedLocalDateTime = givenLocalDateTime.plusDays(1); + manipulatedLocalDateTime = manipulatedLocalDateTime.minusHours(2); + + assertThat(manipulatedLocalDateTime).isEqualTo(LocalDateTime.of(2015, Month.FEBRUARY, 21, 4, 30)); + } + + @Test + public void whenRequestTimeFromEpoch_thenResultIsAsExpected() { + LocalDateTime result = useLocalDateTime.ofEpochSecond(1465817690, ZoneOffset.UTC); + + assertThat(result.toString()).isEqualTo("2016-06-13T11:34:50"); + } } 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 79% 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 index bb9b60956d..fd22be9260 100644 --- 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 @@ -12,7 +12,7 @@ import org.junit.Test; public class UseLocalDateUnitTest { - UseLocalDate useLocalDate = new UseLocalDate(); + private UseLocalDate useLocalDate = new UseLocalDate(); @Test public void givenValues_whenUsingFactoryOf_thenLocalDate() { @@ -88,4 +88,31 @@ public class UseLocalDateUnitTest { assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); } + @Test + public void givenTheYear2000_whenCheckingForLeapYear_thenReturnTrue() { + LocalDate given = LocalDate.parse("2000-06-23"); + + boolean leapYear = useLocalDate.isLeapYear(given); + + assertThat(leapYear).isEqualTo(true); + } + + @Test + public void givenTheYear2004_whenCheckingForLeapYear_thenReturnTrue() { + LocalDate given = LocalDate.parse("2004-06-23"); + + boolean leapYear = useLocalDate.isLeapYear(given); + + assertThat(leapYear).isEqualTo(true); + } + + @Test + public void givenTheYear2019_whenCheckingForLeapYear_thenReturnFalse() { + LocalDate given = LocalDate.parse("2019-06-23"); + + boolean leapYear = useLocalDate.isLeapYear(given); + + assertThat(leapYear).isEqualTo(false); + } + } 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 68% 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 index 996e200ae9..afee9126f9 100644 --- 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 @@ -7,21 +7,30 @@ import org.junit.Test; public class UseLocalTimeUnitTest { - UseLocalTime useLocalTime = new UseLocalTime(); + private UseLocalTime useLocalTime = new UseLocalTime(); @Test public void givenValues_whenUsingFactoryOf_thenLocalTime() { - Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString()); + Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7) + .toString()); + } + + @Test + public void givenValues_whenUsingFactoryOfWithoutSeconds_thenLocalTime() { + Assert.assertEquals("07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7) + .toString()); } @Test public void givenString_whenUsingParse_thenLocalTime() { - Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()); + Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30") + .toString()); } @Test public void givenTime_whenAddHour_thenLocalTime() { - Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString()); + Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)) + .toString()); } @Test 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 67% 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 index f9b4008888..4a39f6056e 100644 --- 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 @@ -7,13 +7,14 @@ import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; +import java.util.Set; import org.junit.Assert; import org.junit.Test; public class UseZonedDateTimeUnitTest { - UseZonedDateTime zonedDateTime = new UseZonedDateTime(); + private UseZonedDateTime zonedDateTime = new UseZonedDateTime(); @Test public void givenZoneId_thenZonedDateTime() { @@ -22,6 +23,13 @@ public class UseZonedDateTimeUnitTest { Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); } + @Test + public void whenRequestingZones_thenAtLeastOneIsReturned() { + Set allZoneIds = ZoneId.getAvailableZoneIds(); + + assertThat(allZoneIds.size()).isGreaterThan(1); + } + @Test public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() { LocalDate given = LocalDate.parse("2018-06-23"); @@ -42,4 +50,15 @@ public class UseZonedDateTimeUnitTest { assertThat(startOfOfDayWithMethod.toLocalTime() .toString()).isEqualTo("00:00"); } + + @Test + public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() { + ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]"); + ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris")); + + assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris")); + assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris")); + + assertThat(resultFromString).isEqualTo(resultFromLocalDateTime); + } } 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-datetime-string/README.md b/core-java-modules/core-java-datetime-string/README.md new file mode 100644 index 0000000000..cf00bdeb1f --- /dev/null +++ b/core-java-modules/core-java-datetime-string/README.md @@ -0,0 +1,13 @@ +## Java Dates Parsing and Formatting Cookbooks and Examples + +This module contains articles about parsing and formatting Java date and time objects. + +### Relevant Articles: +- [Check If a String Is a Valid Date in Java](https://www.baeldung.com/java-string-valid-date) +- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions) +- [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter) +- [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string) +- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format) +- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) +- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp) +- [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) diff --git a/java-dates/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml similarity index 81% rename from java-dates/pom.xml rename to core-java-modules/core-java-datetime-string/pom.xml index 3fddf3f0f8..b4e7aff524 100644 --- a/java-dates/pom.xml +++ b/core-java-modules/core-java-datetime-string/pom.xml @@ -1,17 +1,16 @@ 4.0.0 - com.baeldung - java-dates - 0.1.0-SNAPSHOT - java-dates + core-java-datetime-string + ${project.parent.version} + core-java-datetime-string jar com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java @@ -20,17 +19,17 @@ commons-lang3 ${commons-lang3.version} + + + commons-validator + commons-validator + ${commons-validator.version} + log4j log4j ${log4j.version} - - org.projectlombok - lombok - ${lombok.version} - provided - org.assertj @@ -52,7 +51,7 @@ - java-dates + core-java-datetime-string src/main/resources @@ -74,6 +73,7 @@ + 1.6 2.10 3.6.1 diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidator.java similarity index 100% rename from java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidator.java diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java similarity index 100% rename from java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java similarity index 100% rename from java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java similarity index 100% rename from java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java similarity index 100% rename from java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/DateMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/FormattedDateMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/RangedDateMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java diff --git a/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java diff --git a/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java diff --git a/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java diff --git a/java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java diff --git a/java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/OffsetDateTimeExample.java similarity index 89% rename from java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/OffsetDateTimeExample.java index fb92eb8d0d..90077795f0 100644 --- a/java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java +++ b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/OffsetDateTimeExample.java @@ -1,4 +1,4 @@ -package com.baeldung.zoneddatetime; +package com.baeldung.zonedatetime; import java.time.OffsetDateTime; import java.time.ZoneOffset; diff --git a/java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/OffsetTimeExample.java similarity index 89% rename from java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/OffsetTimeExample.java index 58e2d4d5ad..e280d365c2 100644 --- a/java-dates/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java +++ b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/OffsetTimeExample.java @@ -1,4 +1,4 @@ -package com.baeldung.zoneddatetime; +package com.baeldung.zonedatetime; import java.time.OffsetTime; import java.time.ZoneOffset; diff --git a/java-dates/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/ZoneDateTimeExample.java similarity index 93% rename from java-dates/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java rename to core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/ZoneDateTimeExample.java index b54b8c5225..a0dd304876 100644 --- a/java-dates/src/main/java/com/baeldung/zoneddatetime/ZoneDateTimeExample.java +++ b/core-java-modules/core-java-datetime-string/src/main/java/com/baeldung/zonedatetime/ZoneDateTimeExample.java @@ -1,4 +1,4 @@ -package com.baeldung.zoneddatetime; +package com.baeldung.zonedatetime; import java.time.ZoneId; import java.time.ZonedDateTime; diff --git a/java-dates/src/test/java/com/baeldung/date/StringToDateUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/StringToDateUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/StringToDateUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/StringToDateUnitTest.java diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java similarity index 100% rename from java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java similarity index 100% rename from java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java similarity index 100% rename from java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java similarity index 100% rename from java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/datetime/DateTimeFormatterUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/FormattedDateMatcherUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/RangedDateMatcherUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/February29thMatcherUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/FebruaryGeneralMatcherUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/GregorianDateMatcherUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf30DaysMatcherUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/MonthsOf31DaysMatcherUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/regexp/datepattern/gregorian/testhelper/GregorianDateTestHelper.java diff --git a/java-dates/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/simpledateformat/SimpleDateFormatUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java diff --git a/java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/OffsetDateTimeExampleUnitTest.java similarity index 93% rename from java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/OffsetDateTimeExampleUnitTest.java index a08d3737cd..7634ff1572 100644 --- a/java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetDateTimeExampleUnitTest.java +++ b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/OffsetDateTimeExampleUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.zoneddatetime; +package com.baeldung.zonedatetime; import static org.junit.Assert.assertTrue; diff --git a/java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/OffsetTimeExampleUnitTest.java similarity index 93% rename from java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/OffsetTimeExampleUnitTest.java index 488f934179..6134e48f70 100644 --- a/java-dates/src/test/java/com/baeldung/zoneddatetime/OffsetTimeExampleUnitTest.java +++ b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/OffsetTimeExampleUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.zoneddatetime; +package com.baeldung.zonedatetime; import static org.junit.Assert.assertTrue; diff --git a/java-dates/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/ZoneDateTimeExampleUnitTest.java similarity index 96% rename from java-dates/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/ZoneDateTimeExampleUnitTest.java index e78ff3e3fd..cc19055beb 100644 --- a/java-dates/src/test/java/com/baeldung/zoneddatetime/ZoneDateTimeExampleUnitTest.java +++ b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/ZoneDateTimeExampleUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.zoneddatetime; +package com.baeldung.zonedatetime; import static org.junit.Assert.assertTrue; diff --git a/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/ZonedDateTimeUnitTest.java similarity index 98% rename from java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java rename to core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/ZonedDateTimeUnitTest.java index 65f63bc787..150983c61b 100644 --- a/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java +++ b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/zonedatetime/ZonedDateTimeUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.zoneddatetime; +package com.baeldung.zonedatetime; import static org.junit.jupiter.api.Assertions.assertThrows; diff --git a/core-java-modules/core-java-datetime/README.md b/core-java-modules/core-java-datetime/README.md deleted file mode 100644 index 71aea2e9db..0000000000 --- a/core-java-modules/core-java-datetime/README.md +++ /dev/null @@ -1,7 +0,0 @@ -========= - -## Core Java 8 Cookbooks and Examples - -### Relevant Articles: -- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) -- [Overriding System Time for Testing in Java](https://www.baeldung.com/java-override-system-time) \ No newline at end of file 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-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/pom.xml b/core-java-modules/core-java-io/pom.xml index c3c48ba679..3478f71286 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -50,6 +50,12 @@ jmimemagic ${jmime-magic.version} + + + com.sun.messaging.mq + fscontext + ${fscontext.version} + @@ -154,7 +160,7 @@ 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-jpms/decoupling-pattern2/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml index 757d9229df..09ca44d9be 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.consumermodule consumermodule 1.0 diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml index 4de3df8c01..861f06f089 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule/pom.xml @@ -3,16 +3,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung.servicemodule + servicemodule + 1.0 + >com.baeldung.decoupling-pattern2 decoupling-pattern2 1.0-SNAPSHOT - com.baeldung.servicemodule - servicemodule - 1.0 - 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-2/pom.xml b/core-java-modules/core-java-lang-oop-2/pom.xml index 6e67c76d20..5bca2f0dbf 100644 --- a/core-java-modules/core-java-lang-oop-2/pom.xml +++ b/core-java-modules/core-java-lang-oop-2/pom.xml @@ -28,12 +28,6 @@ test - - - - 3.10.0 - 3.0.3 - core-java-lang-oop-2 @@ -45,4 +39,10 @@ + + + 3.10.0 + 3.0.3 + + diff --git a/core-java-modules/core-java-lang-oop-3/README.md b/core-java-modules/core-java-lang-oop-3/README.md index 4ac6c3ffe9..f8efcb737f 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) diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/FirstClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/FirstClass.java new file mode 100644 index 0000000000..a80387d61a --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/FirstClass.java @@ -0,0 +1,18 @@ +package com.baeldung.core.modifiers; + +public class FirstClass { + + protected String name; + + protected FirstClass(String name) { + this.name = name; + } + + protected String getName() { + return name; + } + + protected static class InnerClass { + public InnerClass() {} + } +} diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/GenericClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/GenericClass.java new file mode 100644 index 0000000000..83381931d0 --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/GenericClass.java @@ -0,0 +1,15 @@ +package com.baeldung.core.modifiers; + +public class GenericClass { + + public static void main(String[] args) { + // accessing protected constructor + FirstClass first = new FirstClass("random name"); + // using protected method + System.out.println("FirstClass name is " + first.getName()); + // accessing a protected field + first.name = "new name"; + // instantiating protected inner class + FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); + } +} diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondClass.java new file mode 100644 index 0000000000..528f97539a --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondClass.java @@ -0,0 +1,18 @@ +package com.baeldung.core.modifiers.otherpackage; + +import com.baeldung.core.modifiers.FirstClass; + +public class SecondClass extends FirstClass { + + public SecondClass(String name) { + // accessing protected constructor + super(name); + // using protected method + System.out.println("SecondClass name is " + this.getName()); + // accessing a protected field + this.name = "new name"; + // instantiating protected inner class -> add public constructor to InnerClass + FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); + } + +} diff --git a/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondGenericClass.java b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondGenericClass.java new file mode 100644 index 0000000000..d29533edef --- /dev/null +++ b/core-java-modules/core-java-lang-syntax-2/src/main/java/com/baeldung/core/modifiers/otherpackage/SecondGenericClass.java @@ -0,0 +1,20 @@ +package com.baeldung.core.modifiers.otherpackage; + +import com.baeldung.core.modifiers.FirstClass; +//import com.baeldung.core.modifiers.FirstClass.InnerClass; + +public class SecondGenericClass { + + // uncomment the following lines to see the errors + public static void main(String[] args) { + // accessing protected constructor + // FirstClass first = new FirstClass("random name"); + // using protected method + // System.out.println("FirstClass name is " + first.getName()); + // accessing a protected field + // first.name = "new name"; + // instantiating protected inner class + // FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); + } + +} 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..7dc33b5e11 100644 --- a/core-java-modules/core-java-networking-2/README.md +++ b/core-java-modules/core-java-networking-2/README.md @@ -9,4 +9,5 @@ This module contains articles about networking in Java - [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) +- [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection) - [[<-- Prev]](/core-java-modules/core-java-networking) 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 f6c5ef04a5..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} + @@ -54,7 +64,7 @@ - + org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin.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-2/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-2/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-2/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/jackson-simple/src/test/resources/.gitignore b/core-java-modules/core-java-streams/src/test/resources/.gitignore similarity index 100% rename from jackson-simple/src/test/resources/.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 89% 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 bebffe52f1..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,14 +1,14 @@ /** * */ -package com.baeldung.string; +package com.baeldung.addchar; /** * @author swpraman * */ public class AppendCharAtPositionX { - + public String addCharUsingCharArray(String str, char ch, int position) { validate(str, position); int len = str.length(); @@ -30,15 +30,14 @@ public class AppendCharAtPositionX { sb.insert(position, ch); return sb.toString(); } - + private void validate(String str, int position) { if (str == null) { throw new IllegalArgumentException("Str should not be null"); } int len = str.length(); if (position < 0 || position > len) { - throw new IllegalArgumentException("position[" + position + "] should be " - + "in the range 0.." + len + " for string " + str); + throw new IllegalArgumentException("position[" + position + "] should be " + "in the range 0.." + len + " for string " + str); } } 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 57% 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 a9cc71d36a..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; @@ -12,10 +12,15 @@ class StringHelper { } static String removeLastCharOptional(String s) { - return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s); + return Optional.ofNullable(s) + .filter(str -> str.length() != 0) + .map(str -> str.substring(0, str.length() - 1)) + .orElse(s); } static String removeLastCharRegexOptional(String s) { - return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s); + return Optional.ofNullable(s) + .map(str -> str.replaceAll(".$", "")) + .orElse(s); } } 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 85% 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 2cdf6145d3..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; @@ -12,99 +12,99 @@ import org.junit.Test; * */ public class AppendCharAtPositionXUnitTest { - + private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX(); private String word = "Titanc"; private char letter = 'i'; - + @Test public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() { assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0)); } - + @Test public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() { assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0)); - } - + } + @Test public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() { assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0)); } - + @Test public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() { assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3)); } - + @Test public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() { assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3)); - } - + } + @Test public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() { assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3)); } - + @Test public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() { assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length())); } - + @Test public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() { assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length())); - } - + } + @Test public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() { assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length())); } - - @Test(expected=IllegalArgumentException.class) + + @Test(expected = IllegalArgumentException.class) public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); } - - @Test(expected=IllegalArgumentException.class) + + @Test(expected = IllegalArgumentException.class) public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); - } - - @Test(expected=IllegalArgumentException.class) + } + + @Test(expected = IllegalArgumentException.class) public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1); } - - @Test(expected=IllegalArgumentException.class) + + @Test(expected = IllegalArgumentException.class) public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); } - - @Test(expected=IllegalArgumentException.class) + + @Test(expected = IllegalArgumentException.class) public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); - } - - @Test(expected=IllegalArgumentException.class) + } + + @Test(expected = IllegalArgumentException.class) public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2); } - - @Test(expected=IllegalArgumentException.class) + + @Test(expected = IllegalArgumentException.class) public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); } - - @Test(expected=IllegalArgumentException.class) + + @Test(expected = IllegalArgumentException.class) public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); - } - - @Test(expected=IllegalArgumentException.class) + } + + @Test(expected = IllegalArgumentException.class) public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() { appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3); } - + } 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 917ed1c937..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,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.removelastchar; import org.apache.commons.lang3.StringUtils; import org.junit.Test; @@ -6,7 +6,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -public class StringHelperUnitTest { +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/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml new file mode 100644 index 0000000000..f1b7499b6d --- /dev/null +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -0,0 +1,73 @@ + + 4.0.0 + core-java-string-algorithms + 0.1.0-SNAPSHOT + jar + core-java-string-algorithms + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.ahocorasick + ahocorasick + ${ahocorasick.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-core.version} + + + com.vdurmont + emoji-java + ${emoji-java.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-string-algorithms + + + src/main/resources + true + + + + + + 3.8.1 + 27.0.1-jre + 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 88% 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 e2dd0ac1db..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; @@ -10,7 +10,6 @@ import org.junit.Test; import com.google.common.base.CharMatcher; - /*** * Example of counting chars in a String. */ @@ -78,16 +77,21 @@ public class CountCharsExampleUnitTest { @Test public void givenString_whenUsingJava8Features_thenCountChars() { String someString = "elephant"; - long count = someString.chars().filter(ch -> ch == 'e').count(); + long count = someString.chars() + .filter(ch -> ch == 'e') + .count(); assertEquals(2, count); - long count2 = someString.codePoints().filter(ch -> ch == 'e').count(); + long count2 = someString.codePoints() + .filter(ch -> ch == 'e') + .count(); assertEquals(2, count2); } @Test public void givenString_whenUsingGuavaCharMatcher_thenCountChars() { - int count = CharMatcher.is('e').countIn("elephant"); + int count = CharMatcher.is('e') + .countIn("elephant"); assertEquals(2, count); } 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 97% 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 49f2542f39..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,6 +1,7 @@ -package com.baeldung.string; +package com.baeldung.palindrom; + +import static org.junit.Assert.assertTrue; -import static org.junit.Assert.*; import org.junit.Test; public class PalindromeUnitTest { @@ -20,9 +21,9 @@ public class PalindromeUnitTest { "No mists or frost Simon", "Stella won no wallets" }; - + private Palindrome palindrome = new Palindrome(); - + @Test public void whenWord_shouldBePalindrome() { for (String word : words) 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/core-java-modules/core-java-string-apis/README.md b/core-java-modules/core-java-string-apis/README.md new file mode 100644 index 0000000000..fc36ba8640 --- /dev/null +++ b/core-java-modules/core-java-string-apis/README.md @@ -0,0 +1,12 @@ +## Java String APIs + +This module contains articles about string APIs. + +### Relevant Articles: +- [Java 8 StringJoiner](https://www.baeldung.com/java-string-joiner) +- [Quick Guide to the Java StringTokenizer](https://www.baeldung.com/java-stringtokenizer) +- [Guide to java.util.Formatter](https://www.baeldung.com/java-string-formatter) +- [Guide to StreamTokenizer](https://www.baeldung.com/java-streamtokenizer) +- [CharSequence vs. String in Java](https://www.baeldung.com/java-char-sequence-string) +- [StringBuilder and StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer) +- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) diff --git a/core-java-modules/core-java-string-apis/pom.xml b/core-java-modules/core-java-string-apis/pom.xml new file mode 100644 index 0000000000..7d9d888fa1 --- /dev/null +++ b/core-java-modules/core-java-string-apis/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + core-java-string-apis + 0.1.0-SNAPSHOT + jar + core-java-string-apis + + + 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} + + + + org.passay + passay + ${passay.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + + + core-java-string-apis + + + src/main/resources + true + + + + + + 1.3.1 + 1.4 + + + diff --git a/java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java b/core-java-modules/core-java-string-apis/src/main/java/com/baeldung/password/RandomPasswordGenerator.java similarity index 99% rename from java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java rename to core-java-modules/core-java-string-apis/src/main/java/com/baeldung/password/RandomPasswordGenerator.java index 46af4d7c51..d49b13c9c9 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java +++ b/core-java-modules/core-java-string-apis/src/main/java/com/baeldung/password/RandomPasswordGenerator.java @@ -1,4 +1,11 @@ -package com.baeldung.string.password; +package com.baeldung.password; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.text.RandomStringGenerator; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.CharacterData; +import org.passay.PasswordGenerator; import java.security.SecureRandom; import java.util.Collections; @@ -8,13 +15,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.text.RandomStringGenerator; -import org.passay.CharacterData; -import org.passay.CharacterRule; -import org.passay.EnglishCharacterData; -import org.passay.PasswordGenerator; - public class RandomPasswordGenerator { /** diff --git a/java-strings-2/src/main/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemo.java b/core-java-modules/core-java-string-apis/src/main/java/com/baeldung/streamtokenizer/StreamTokenizerDemo.java similarity index 98% rename from java-strings-2/src/main/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemo.java rename to core-java-modules/core-java-string-apis/src/main/java/com/baeldung/streamtokenizer/StreamTokenizerDemo.java index 3bb0ff5b77..5ab506f259 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemo.java +++ b/core-java-modules/core-java-string-apis/src/main/java/com/baeldung/streamtokenizer/StreamTokenizerDemo.java @@ -1,4 +1,4 @@ -package com.baeldung.string.streamtokenizer; +package com.baeldung.streamtokenizer; import java.io.*; import java.util.ArrayList; diff --git a/java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java b/core-java-modules/core-java-string-apis/src/main/java/com/baeldung/stringbuilderstringbuffer/StringBuilderStringBuffer.java similarity index 89% rename from java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java rename to core-java-modules/core-java-string-apis/src/main/java/com/baeldung/stringbuilderstringbuffer/StringBuilderStringBuffer.java index 72af4a9aee..50c139e2d3 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java +++ b/core-java-modules/core-java-string-apis/src/main/java/com/baeldung/stringbuilderstringbuffer/StringBuilderStringBuffer.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.stringbuilderstringbuffer; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; @@ -8,12 +8,12 @@ import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; -public class StringBufferStringBuilder { +public class StringBuilderStringBuffer { public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() - .include(StringBufferStringBuilder.class.getSimpleName()) + .include(StringBuilderStringBuffer.class.getSimpleName()) .build(); new Runner(opt).run(); diff --git a/java-strings/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/core-java-modules/core-java-string-apis/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java rename to core-java-modules/core-java-string-apis/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java diff --git a/java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/charsequence/CharSequenceVsStringUnitTest.java similarity index 97% rename from java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/charsequence/CharSequenceVsStringUnitTest.java index 916a3c79ff..aa15345bcb 100644 --- a/java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/charsequence/CharSequenceVsStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.charsequence; import org.junit.Test; diff --git a/java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/formatter/StringFormatterExampleUnitTest.java similarity index 96% rename from java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/formatter/StringFormatterExampleUnitTest.java index 648fdaf65a..549c889028 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/formatter/StringFormatterExampleUnitTest.java @@ -1,12 +1,12 @@ -package com.baeldung.string.formatter; +package com.baeldung.formatter; + +import org.junit.Test; import java.util.Calendar; import java.util.Formatter; import java.util.GregorianCalendar; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Test; + +import static org.junit.Assert.*; public class StringFormatterExampleUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/password/StringPasswordUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/password/StringPasswordUnitTest.java index bfd4b0fe8e..7fb55ad1cb 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/password/StringPasswordUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.password; - -import static org.junit.Assert.assertTrue; +package com.baeldung.password; import org.junit.Test; +import static org.junit.Assert.assertTrue; + /** * Examples of passwords conforming to various specifications, using different libraries. * diff --git a/java-strings-2/src/test/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemoUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/streamtokenizer/StreamTokenizerDemoUnitTest.java similarity index 96% rename from java-strings-2/src/test/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemoUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/streamtokenizer/StreamTokenizerDemoUnitTest.java index 01091ec629..29214167be 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemoUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/streamtokenizer/StreamTokenizerDemoUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.streamtokenizer; +package com.baeldung.streamtokenizer; import org.junit.Test; diff --git a/java-strings/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java index a72f811336..89f91acd6e 100644 --- a/java-strings/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringjoiner/StringJoinerUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.stringjoiner; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; @@ -8,7 +8,7 @@ import java.util.List; import java.util.StringJoiner; import java.util.stream.Collectors; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class StringJoinerUnitTest { private final String DELIMITER_COMMA = ","; diff --git a/java-strings/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringtokenizer/TokenizerUnitTest.java diff --git a/core-java-modules/core-java-string-apis/src/test/resources/data.csv b/core-java-modules/core-java-string-apis/src/test/resources/data.csv new file mode 100644 index 0000000000..ec4ac10443 --- /dev/null +++ b/core-java-modules/core-java-string-apis/src/test/resources/data.csv @@ -0,0 +1,3 @@ +1|IND|India +2|MY|Malaysia +3|AU|Australia diff --git a/java-strings-2/src/main/resources/stream-tokenizer-example.txt b/core-java-modules/core-java-string-apis/src/test/resources/stream-tokenizer-example.txt similarity index 100% rename from java-strings-2/src/main/resources/stream-tokenizer-example.txt rename to core-java-modules/core-java-string-apis/src/test/resources/stream-tokenizer-example.txt 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/core-java-modules/core-java-string-operations/pom.xml b/core-java-modules/core-java-string-operations/pom.xml new file mode 100644 index 0000000000..fdddd99433 --- /dev/null +++ b/core-java-modules/core-java-string-operations/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + core-java-string-operations + 0.1.0-SNAPSHOT + jar + core-java-string-operations + + + 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} + + + log4j + log4j + ${log4j.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-string-operations + + + src/main/resources + true + + + + + + 3.8.1 + 3.6.1 + 1.10 + + + diff --git a/java-strings/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/Benchmarking.java similarity index 85% rename from java-strings/src/main/java/com/baeldung/stringisnumeric/Benchmarking.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/Benchmarking.java index 4ae1f5aa83..97e7a46757 100644 --- a/java-strings/src/main/java/com/baeldung/stringisnumeric/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.stringisnumeric; +package com.baeldung.isnumeric; import java.util.concurrent.TimeUnit; @@ -13,13 +13,11 @@ import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; - public class Benchmarking { public static void main(String[] args) throws RunnerException { - Options opt = new OptionsBuilder() - .include(Benchmarking.class.getSimpleName()) - .forks(1) - .build(); + Options opt = new OptionsBuilder().include(Benchmarking.class.getSimpleName()) + .forks(1) + .build(); new Runner(opt).run(); } @@ -28,45 +26,45 @@ public class Benchmarking { public static class ExecutionPlan { public String number = Integer.toString(Integer.MAX_VALUE); public boolean isNumber = false; - public IsNumeric isNumeric= new IsNumeric(); + public IsNumeric isNumeric = new IsNumeric(); } - - @Benchmark + + @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingCoreJava(ExecutionPlan plan) { plan.isNumber = plan.isNumeric.usingCoreJava(plan.number); } - - @Benchmark + + @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingRegularExpressions(ExecutionPlan plan) { plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number); } - - @Benchmark + + @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingNumberUtils_isCreatable(ExecutionPlan plan) { plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number); } - - @Benchmark + + @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingNumberUtils_isParsable(ExecutionPlan plan) { plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number); } - - @Benchmark + + @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingStringUtils_isNumeric(ExecutionPlan plan) { plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number); } - - @Benchmark + + @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingStringUtils_isNumericSpace(ExecutionPlan plan) { diff --git a/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/CheckIntegerInput.java similarity index 89% rename from java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/CheckIntegerInput.java index 9462244bbb..6c08615c74 100644 --- a/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/CheckIntegerInput.java @@ -1,14 +1,13 @@ -package com.baeldung.string.checkinputs; +package com.baeldung.isnumeric; import java.util.Scanner; public class CheckIntegerInput { public static void main(String[] args) { - try (Scanner scanner = new Scanner(System.in)) { System.out.println("Enter an integer : "); - + if (scanner.hasNextInt()) { System.out.println("You entered : " + scanner.nextInt()); } else { diff --git a/java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumeric.java similarity index 88% rename from java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumeric.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumeric.java index c438071e42..6eed0d777d 100644 --- a/java-strings/src/main/java/com/baeldung/stringisnumeric/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.stringisnumeric; +package com.baeldung.isnumeric; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; @@ -6,29 +6,29 @@ import org.apache.commons.lang3.math.NumberUtils; public class IsNumeric { public boolean usingCoreJava(String strNum) { try { - double d = Double.parseDouble(strNum); + Double.parseDouble(strNum); } catch (NumberFormatException | NullPointerException nfe) { return false; } return true; } - + public boolean usingRegularExpressions(String strNum) { return strNum.matches("-?\\d+(\\.\\d+)?"); } - + public boolean usingNumberUtils_isCreatable(String strNum) { return NumberUtils.isCreatable(strNum); } - + public boolean usingNumberUtils_isParsable(String strNum) { return NumberUtils.isParsable(strNum); } - + public boolean usingStringUtils_isNumeric(String strNum) { return StringUtils.isNumeric(strNum); } - + public boolean usingStringUtils_isNumericSpace(String strNum) { return StringUtils.isNumericSpace(strNum); } diff --git a/java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumericDriver.java similarity index 60% rename from java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java rename to core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumericDriver.java index c0a6edae50..a6c5449696 100644 --- a/java-strings/src/main/java/com/baeldung/stringisnumeric/IsNumericDriver.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/isnumeric/IsNumericDriver.java @@ -1,34 +1,31 @@ -package com.baeldung.stringisnumeric; +package com.baeldung.isnumeric; import org.apache.log4j.Logger; public class IsNumericDriver { - private static IsNumeric isNumeric; private static Logger LOG = Logger.getLogger(IsNumericDriver.class); - static { - isNumeric =new IsNumeric(); - - } - + + private static IsNumeric isNumeric = new IsNumeric(); + public static void main(String[] args) { LOG.info("Testing all methods..."); - + boolean res = isNumeric.usingCoreJava("1001"); LOG.info("Using Core Java : " + res); - + res = isNumeric.usingRegularExpressions("1001"); LOG.info("Using Regular Expressions : " + res); - - res =isNumeric.usingNumberUtils_isCreatable("1001"); + + res = isNumeric.usingNumberUtils_isCreatable("1001"); LOG.info("Using NumberUtils.isCreatable : " + res); - - res =isNumeric.usingNumberUtils_isParsable("1001"); + + res = isNumeric.usingNumberUtils_isParsable("1001"); LOG.info("Using NumberUtils.isParsable : " + res); - - res =isNumeric.usingStringUtils_isNumeric("1001"); + + res = isNumeric.usingStringUtils_isNumeric("1001"); LOG.info("Using StringUtils.isNumeric : " + res); - - res =isNumeric.usingStringUtils_isNumericSpace("1001"); + + res = isNumeric.usingStringUtils_isNumericSpace("1001"); LOG.info("Using StringUtils.isNumericSpace : " + res); } } 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 63% 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 e914a83f0e..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,19 +1,22 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class Customer { private String firstName; private String lastName; - + public String getFirstName() { - return firstName; + return firstName; } + public void setFirstName(String firstName) { - this.firstName = firstName; + this.firstName = firstName; } + public String getLastName() { - return lastName; + return lastName; } + public void setLastName(String lastName) { - this.lastName = lastName; + this.lastName = lastName; } } 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 61% 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 1736657276..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,19 +1,20 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import java.util.Arrays; public class CustomerArrayToString extends Customer { private Order[] orders; - + public Order[] getOrders() { return orders; } + public void setOrders(Order[] orders) { this.orders = orders; } + @Override public String toString() { - return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName() - + ", getLastName()=" + getLastName() + "]"; - } + return "Customer [orders=" + Arrays.toString(orders) + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]"; + } } 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 60% 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 9bede1b3fc..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,8 +1,8 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class CustomerComplexObjectToString extends Customer { private Order order; - + public Order getOrder() { return order; } @@ -13,7 +13,6 @@ public class CustomerComplexObjectToString extends Customer { @Override public String toString() { - return "Customer [order=" + order + ", getFirstName()=" + getFirstName() - + ", getLastName()=" + getLastName() + "]"; - } + return "Customer [order=" + order + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]"; + } } \ No newline at end of file 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 61% 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 86e08ca447..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,19 +1,18 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class CustomerPrimitiveToString extends Customer { private long balance; - + public long getBalance() { return balance; } - + public void setBalance(long balance) { this.balance = balance; } - + @Override public String toString() { - return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName() - + ", getLastName()=" + getLastName() + "]"; + return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]"; } } 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 85% 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 2da1163c63..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,39 +1,39 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import java.util.List; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -public class CustomerReflectionToString extends Customer{ +public class CustomerReflectionToString extends Customer { private Integer score; private List orders; private StringBuffer fullname; - + public Integer getScore() { return score; } - + public void setScore(Integer score) { this.score = score; } - + public List getOrders() { return orders; } - + public void setOrders(List orders) { this.orders = orders; } - + public StringBuffer getFullname() { return fullname; } - + public void setFullname(StringBuffer fullname) { this.fullname = fullname; } - + @Override public String toString() { return ReflectionToStringBuilder.toString(this); diff --git a/java-strings-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 74% 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 6c7b999045..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; @@ -6,34 +6,33 @@ public class CustomerWrapperCollectionToString extends Customer { private Integer score; private List orders; private StringBuffer fullname; - + public Integer getScore() { return score; } - + public void setScore(Integer score) { this.score = score; } - + public List getOrders() { return orders; } - + public void setOrders(List orders) { this.orders = orders; } - + public StringBuffer getFullname() { return fullname; } - + public void setFullname(StringBuffer fullname) { this.fullname = fullname; } - + @Override public String toString() { - return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname - + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]"; + return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]"; } } 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 91% 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 017e2d9bc8..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,7 +1,7 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; public class Order { - + private String orderId; private String desc; private long value; @@ -38,9 +38,10 @@ public class Order { public void setStatus(String status) { this.status = status; } + @Override public String toString() { - return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]"; + return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]"; } } diff --git a/core-java-modules/core-java-string-operations/src/main/resources/log4j.properties b/core-java-modules/core-java-string-operations/src/main/resources/log4j.properties new file mode 100644 index 0000000000..2ea9fa9209 --- /dev/null +++ b/core-java-modules/core-java-string-operations/src/main/resources/log4j.properties @@ -0,0 +1,8 @@ +# Root logger option +log4j.rootLogger=DEBUG, stdout + +# Redirect log messages to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file 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/stringisnumeric/CoreJavaIsNumericUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/CoreJavaIsNumericUnitTest.java similarity index 89% rename from java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/CoreJavaIsNumericUnitTest.java index 808d3c45b0..6c03b00e69 100644 --- a/java-strings-ops/src/test/java/com/baeldung/stringisnumeric/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.stringisnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; @@ -13,16 +13,16 @@ public class CoreJavaIsNumericUnitTest { } return true; } - + @Test public void whenUsingCoreJava_thenTrue() { // Valid Numbers assertThat(isNumeric("22")).isTrue(); assertThat(isNumeric("5.05")).isTrue(); - assertThat(isNumeric("-200")).isTrue(); + assertThat(isNumeric("-200")).isTrue(); assertThat(isNumeric("10.0d")).isTrue(); assertThat(isNumeric(" 22 ")).isTrue(); - + // Invalid Numbers assertThat(isNumeric(null)).isFalse(); assertThat(isNumeric("")).isFalse(); diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsCreatableUnitTest.java similarity index 95% rename from java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsCreatableUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsCreatableUnitTest.java index 467d58837a..3b88721ad4 100644 --- a/java-strings/src/test/java/com/baeldung/stringisnumeric/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.stringisnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; @@ -17,7 +17,7 @@ public class NumberUtilsIsCreatableUnitTest { assertThat(NumberUtils.isCreatable("0xFF")).isTrue(); assertThat(NumberUtils.isCreatable("07")).isTrue(); assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue(); - + // Invalid Numbers assertThat(NumberUtils.isCreatable(null)).isFalse(); assertThat(NumberUtils.isCreatable("")).isFalse(); diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsParsableUnitTest.java similarity index 95% rename from java-strings/src/test/java/com/baeldung/stringisnumeric/NumberUtilsIsParsableUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/NumberUtilsIsParsableUnitTest.java index 141a761158..6b96a6efa1 100644 --- a/java-strings/src/test/java/com/baeldung/stringisnumeric/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.stringisnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; @@ -13,7 +13,7 @@ public class NumberUtilsIsParsableUnitTest { assertThat(NumberUtils.isParsable("-23")).isTrue(); assertThat(NumberUtils.isParsable("2.2")).isTrue(); assertThat(NumberUtils.isParsable("09")).isTrue(); - + // Invalid Numbers assertThat(NumberUtils.isParsable(null)).isFalse(); assertThat(NumberUtils.isParsable("")).isFalse(); diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/RegularExpressionsUnitTest.java similarity index 91% rename from java-strings/src/test/java/com/baeldung/stringisnumeric/RegularExpressionsUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/RegularExpressionsUnitTest.java index c3aa43ac94..04f3de8dc5 100644 --- a/java-strings/src/test/java/com/baeldung/stringisnumeric/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.stringisnumeric; +package com.baeldung.isnumeric; import static org.assertj.core.api.Assertions.assertThat; @@ -8,14 +8,14 @@ public class RegularExpressionsUnitTest { public static boolean isNumeric(String strNum) { return strNum.matches("-?\\d+(\\.\\d+)?"); } - + @Test public void whenUsingRegularExpressions_thenTrue() { // Valid Numbers assertThat(isNumeric("22")).isTrue(); assertThat(isNumeric("5.05")).isTrue(); assertThat(isNumeric("-200")).isTrue(); - + // Invalid Numbers assertThat(isNumeric("abc")).isFalse(); } diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericSpaceUnitTest.java similarity index 94% rename from java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericSpaceUnitTest.java index 135780d9ad..0c5e52580f 100644 --- a/java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericSpaceUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericSpaceUnitTest.java @@ -1,8 +1,9 @@ -package com.baeldung.stringisnumeric; +package com.baeldung.isnumeric; + +import static org.assertj.core.api.Assertions.assertThat; import org.apache.commons.lang3.StringUtils; import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThat; public class StringUtilsIsNumericSpaceUnitTest { @Test @@ -13,7 +14,7 @@ public class StringUtilsIsNumericSpaceUnitTest { assertThat(StringUtils.isNumericSpace("")).isTrue(); assertThat(StringUtils.isNumericSpace(" ")).isTrue(); assertThat(StringUtils.isNumericSpace("12 3")).isTrue(); - + // Invalid Numbers assertThat(StringUtils.isNumericSpace(null)).isFalse(); assertThat(StringUtils.isNumericSpace("ab2c")).isFalse(); diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/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/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java rename to core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericUnitTest.java index b667dda906..660426cdbb 100644 --- a/java-strings/src/test/java/com/baeldung/stringisnumeric/StringUtilsIsNumericUnitTest.java +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/isnumeric/StringUtilsIsNumericUnitTest.java @@ -1,8 +1,9 @@ -package com.baeldung.stringisnumeric; +package com.baeldung.isnumeric; + +import static org.assertj.core.api.Assertions.assertThat; import org.apache.commons.lang3.StringUtils; import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThat; public class StringUtilsIsNumericUnitTest { @Test @@ -11,7 +12,7 @@ public class StringUtilsIsNumericUnitTest { assertThat(StringUtils.isNumeric("123")).isTrue(); assertThat(StringUtils.isNumeric("١٢٣")).isTrue(); assertThat(StringUtils.isNumeric("१२३")).isTrue(); - + // Invalid Numbers assertThat(StringUtils.isNumeric(null)).isFalse(); assertThat(StringUtils.isNumeric("")).isFalse(); diff --git a/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/split/SplitUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/split/SplitUnitTest.java new file mode 100644 index 0000000000..eaa61e5041 --- /dev/null +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/split/SplitUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.split; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.Test; + +import com.google.common.base.Splitter; + +public class SplitUnitTest { + + @Test + public void givenString_whenSplit_thenReturnsArray_through_JavaLangString() { + assertThat("peter,james,thomas".split(",")).containsExactly("peter", "james", "thomas"); + + assertThat("car jeep scooter".split(" ")).containsExactly("car", "jeep", "scooter"); + + assertThat("1-120-232323".split("-")).containsExactly("1", "120", "232323"); + + assertThat("192.168.1.178".split("\\.")).containsExactly("192", "168", "1", "178"); + + assertThat("b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*")).containsExactly("b", "a", "e", "l", "d", "u", "n", "g"); + } + + @Test + public void givenString_whenSplit_thenReturnsArray_through_StringUtils() { + StringUtils.split("car jeep scooter"); + + assertThat(StringUtils.split("car jeep scooter")).containsExactly("car", "jeep", "scooter"); + + assertThat(StringUtils.split("car jeep scooter")).containsExactly("car", "jeep", "scooter"); + + assertThat(StringUtils.split("car:jeep:scooter", ":")).containsExactly("car", "jeep", "scooter"); + + assertThat(StringUtils.split("car.jeep.scooter", ".")).containsExactly("car", "jeep", "scooter"); + } + + @Test + public void givenString_whenSplit_thenReturnsList_Splitter() { + // given + List resultList = Splitter.on(',') + .trimResults() + .omitEmptyStrings() + .splitToList("car,jeep,, scooter"); + + assertThat(resultList).containsExactly("car", "jeep", "scooter"); + } + + @Test + public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_Regex() { + assertThat(" car , jeep, scooter ".trim() + .split("\\s*,\\s*")).containsExactly("car", "jeep", "scooter"); + + } + + @Test + public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_java_8() { + assertThat(Arrays.stream(" car , jeep, scooter ".split(",")) + .map(String::trim) + .toArray(String[]::new)).containsExactly("car", "jeep", "scooter"); + } +} 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 92% 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 539f66d9b4..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,16 +1,16 @@ -package com.baeldung.string; +package com.baeldung.stringcomparison; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.junit.Test; -import java.util.Objects; - -import static org.assertj.core.api.Assertions.assertThat; - public class StringComparisonUnitTest { @Test - public void whenUsingComparisonOperator_ThenComparingStrings(){ + public void whenUsingComparisonOperator_ThenComparingStrings() { String string1 = "using comparison operator"; String string2 = "using comparison operator"; @@ -21,7 +21,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingEqualsMethod_ThenComparingStrings(){ + public void whenUsingEqualsMethod_ThenComparingStrings() { String string1 = "using equals method"; String string2 = "using equals method"; @@ -37,7 +37,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingEqualsIgnoreCase_ThenComparingStrings(){ + public void whenUsingEqualsIgnoreCase_ThenComparingStrings() { String string1 = "using equals ignore case"; String string2 = "USING EQUALS IGNORE CASE"; @@ -46,7 +46,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingCompareTo_ThenComparingStrings(){ + public void whenUsingCompareTo_ThenComparingStrings() { String author = "author"; String book = "book"; @@ -58,7 +58,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingCompareToIgnoreCase_ThenComparingStrings(){ + public void whenUsingCompareToIgnoreCase_ThenComparingStrings() { String author = "Author"; String book = "book"; @@ -70,7 +70,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingObjectsEqualsMethod_ThenComparingStrings(){ + public void whenUsingObjectsEqualsMethod_ThenComparingStrings() { String string1 = "using objects equals"; String string2 = "using objects equals"; @@ -84,7 +84,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingEqualsOfApacheCommons_ThenComparingStrings(){ + public void whenUsingEqualsOfApacheCommons_ThenComparingStrings() { assertThat(StringUtils.equals(null, null)).isTrue(); assertThat(StringUtils.equals(null, "equals method")).isFalse(); @@ -93,7 +93,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings(){ + public void whenUsingEqualsIgnoreCaseOfApacheCommons_ThenComparingStrings() { assertThat(StringUtils.equalsIgnoreCase(null, null)).isTrue(); assertThat(StringUtils.equalsIgnoreCase(null, "equals method")).isFalse(); @@ -102,7 +102,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingEqualsAnyOf_ThenComparingStrings(){ + public void whenUsingEqualsAnyOf_ThenComparingStrings() { assertThat(StringUtils.equalsAny(null, null, null)).isTrue(); assertThat(StringUtils.equalsAny("equals any", "equals any", "any")).isTrue(); @@ -112,18 +112,17 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings(){ + public void whenUsingEqualsAnyIgnoreCase_ThenComparingStrings() { assertThat(StringUtils.equalsAnyIgnoreCase(null, null, null)).isTrue(); assertThat(StringUtils.equalsAnyIgnoreCase("equals any", "equals any", "any")).isTrue(); assertThat(StringUtils.equalsAnyIgnoreCase("equals any", null, "equals any")).isTrue(); assertThat(StringUtils.equalsAnyIgnoreCase(null, "equals", "any")).isFalse(); - assertThat(StringUtils.equalsAnyIgnoreCase( - "equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue(); + assertThat(StringUtils.equalsAnyIgnoreCase("equals any ignore case", "EQUALS ANY IGNORE CASE", "any")).isTrue(); } @Test - public void whenUsingCompare_thenComparingStringsWithNulls(){ + public void whenUsingCompare_thenComparingStringsWithNulls() { assertThat(StringUtils.compare(null, null)).isEqualTo(0); assertThat(StringUtils.compare(null, "abc")).isEqualTo(-1); @@ -134,7 +133,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls(){ + public void whenUsingCompareIgnoreCase_ThenComparingStringsWithNulls() { assertThat(StringUtils.compareIgnoreCase(null, null)).isEqualTo(0); assertThat(StringUtils.compareIgnoreCase(null, "abc")).isEqualTo(-1); @@ -145,7 +144,7 @@ public class StringComparisonUnitTest { } @Test - public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings(){ + public void whenUsingCompareWithNullIsLessOption_ThenComparingStrings() { assertThat(StringUtils.compare(null, "abc", true)).isEqualTo(-1); assertThat(StringUtils.compare(null, "abc", false)).isEqualTo(1); 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/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerArrayToStringUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerArrayToStringUnitTest.java new file mode 100644 index 0000000000..a754ed3c68 --- /dev/null +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerArrayToStringUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class CustomerArrayToStringUnitTest { + private static final String CUSTOMER_ARRAY_TO_STRING = "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenArray_whenToString_thenCustomerDetails() { + CustomerArrayToString customer = new CustomerArrayToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + Order[] orders = new Order[1]; + orders[0] = new Order(); + orders[0].setOrderId("A1111"); + orders[0].setDesc("Game"); + orders[0].setStatus("In-Shiping"); + customer.setOrders(orders); + + assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString()); + } + +} diff --git a/java-strings-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 69% 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 5ffb0d0e58..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,24 +1,23 @@ -package com.baeldung.string.tostring; +package com.baeldung.tostring; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CustomerComplexObjectToStringUnitTest { - private static final String CUSTOMER_COMPLEX_TO_STRING - = "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]"; - + private static final String CUSTOMER_COMPLEX_TO_STRING = "Customer [order=Order [orderId=A1111, desc=Game, value=0], getFirstName()=Rajesh, getLastName()=Bhojwani]"; + @Test public void givenComplex_whenToString_thenCustomerDetails() { CustomerComplexObjectToString customer = new CustomerComplexObjectToString(); customer.setFirstName("Rajesh"); customer.setLastName("Bhojwani"); - Order order = new Order(); + Order order = new Order(); order.setOrderId("A1111"); order.setDesc("Game"); order.setStatus("In-Shiping"); customer.setOrder(order); - + assertEquals(CUSTOMER_COMPLEX_TO_STRING, customer.toString()); } diff --git a/java-strings-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 72% 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 d43733bc60..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; @@ -6,8 +6,7 @@ import org.junit.jupiter.api.Test; public class CustomerPrimitiveToStringUnitTest { - private static final String CUSTOMER_PRIMITIVE_TO_STRING - = "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]"; + private static final String CUSTOMER_PRIMITIVE_TO_STRING = "Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]"; @Test public void givenPrimitive_whenToString_thenCustomerDetails() { @@ -15,8 +14,7 @@ public class CustomerPrimitiveToStringUnitTest { customer.setFirstName("Rajesh"); customer.setLastName("Bhojwani"); customer.setBalance(110); - + assertEquals(CUSTOMER_PRIMITIVE_TO_STRING, customer.toString()); } } - diff --git a/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerWrapperCollectionToStringUnitTest.java b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerWrapperCollectionToStringUnitTest.java new file mode 100644 index 0000000000..da4937ccdd --- /dev/null +++ b/core-java-modules/core-java-string-operations/src/test/java/com/baeldung/tostring/CustomerWrapperCollectionToStringUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.tostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class CustomerWrapperCollectionToStringUnitTest { + private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING = "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]"; + + @Test + public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() { + CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString(); + customer.setFirstName("Rajesh"); + customer.setLastName("Bhojwani"); + customer.setScore(8); + + List orders = new ArrayList(); + orders.add("Book"); + orders.add("Pen"); + customer.setOrders(orders); + + StringBuffer fullname = new StringBuffer(); + fullname.append(customer.getLastName() + ", " + customer.getFirstName()); + customer.setFullname(fullname); + + assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString()); + } + +} diff --git a/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-datetime/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml similarity index 61% rename from core-java-modules/core-java-datetime/pom.xml rename to core-java-modules/core-java-time-measurements/pom.xml index 800c29ef99..0ff3787051 100644 --- a/core-java-modules/core-java-datetime/pom.xml +++ b/core-java-modules/core-java-time-measurements/pom.xml @@ -1,19 +1,32 @@ - - 4.0.0 - core-java-datetime - 0.1.0-SNAPSHOT - core-java-datetime - jar + + 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 - + + 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 @@ -26,6 +39,11 @@ joda-time ${joda.version} + + org.aspectj + aspectjrt + ${asspectj.version} + org.powermock powermock-module-junit4 @@ -47,7 +65,7 @@ - core-java-datetime + core-java-time-measurements src/main/resources @@ -71,9 +89,11 @@ + 3.6.1 2.10 3.6.1 + 1.8.9 2.0.0-RC.4 1.44 diff --git a/java-streams/src/main/resources/logback.xml b/core-java-modules/core-java-time-measurements/src/main/resources/logback.xml similarity index 100% rename from java-streams/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-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/ddd/pom.xml b/ddd/pom.xml index 4ac65ea841..c249007ba4 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -3,7 +3,6 @@ 4.0.0 com.baeldung.ddd ddd - 0.0.1-SNAPSHOT ddd jar DDD series examples @@ -35,7 +34,6 @@ org.junit.platform junit-platform-launcher - ${junit-platform.version} test @@ -85,8 +83,6 @@ 1.0.1 - 2.22.0 - 2.0.6.RELEASE \ No newline at end of file diff --git a/disruptor/pom.xml b/disruptor/pom.xml index e1d78e7ed6..213331f25c 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung disruptor 0.1.0-SNAPSHOT disruptor @@ -116,10 +115,7 @@ 3.3.6 - - 6.10 - 3.6.1 - + 2.4.3 3.0.2 1.4.4 diff --git a/dozer/pom.xml b/dozer/pom.xml index 8234eb4c79..c781962d83 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung dozer 1.0 dozer diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 9fe228bf89..947175b6a0 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -32,7 +32,6 @@ 2.5.7 3.4.11 0.10 - 2.19.1 diff --git a/ethereum/pom.xml b/ethereum/pom.xml index 80e1c04676..148909e787 100644 --- a/ethereum/pom.xml +++ b/ethereum/pom.xml @@ -1,9 +1,8 @@ + 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 - 0.0.1-SNAPSHOT ethereum @@ -207,8 +206,6 @@ - UTF-8 - 8.5.4 1.5.0-RELEASE 3.3.1 1.5.6.RELEASE @@ -218,5 +215,4 @@ 1.7.25 2.0.4.RELEASE - diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index e8b327e35f..49bd6bd9fd 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung flyway-cdi-extension 1.0-SNAPSHOT flyway-cdi-extension @@ -51,8 +50,6 @@ - 1.8 - 1.8 2.0.SP1 3.0.5.Final 5.1.4 diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index 0723cd3be2..8a7cb87701 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -5,7 +5,6 @@ 4.0.0 - com.baeldung google-web-toolkit 1.0-SNAPSHOT google-web-toolkit diff --git a/gradle-5/README.md b/gradle-5/README.md new file mode 100644 index 0000000000..7c9aeff07e --- /dev/null +++ b/gradle-5/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Run a Java main Method Using Gradle](https://www.baeldung.com/gradle-run-java-main) diff --git a/gson/pom.xml b/gson/pom.xml index 9d2cf630d0..4aa6c00458 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -2,7 +2,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung gson 0.1-SNAPSHOT gson diff --git a/guava-collections-map/pom.xml b/guava-collections-map/pom.xml index 45bb6b8caa..21597d0e28 100644 --- a/guava-collections-map/pom.xml +++ b/guava-collections-map/pom.xml @@ -13,9 +13,6 @@ ../parent-java - - - guava-collections-map @@ -26,7 +23,4 @@ - - - \ No newline at end of file diff --git a/guava-collections-set/pom.xml b/guava-collections-set/pom.xml index 46dcae492d..640a28c4c1 100644 --- a/guava-collections-set/pom.xml +++ b/guava-collections-set/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava-collections-set 0.1.0-SNAPSHOT guava-collections-set @@ -28,8 +27,6 @@ - - 27.1-jre 3.6.1 diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index 8cdb086029..9dfcceaab8 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava-collections 0.1.0-SNAPSHOT guava-collections @@ -54,7 +53,6 @@ - 24.0-jre 4.1 diff --git a/guava-io/pom.xml b/guava-io/pom.xml index 2a66baba80..aaaf7edd4e 100644 --- a/guava-io/pom.xml +++ b/guava-io/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava-io 0.1.0-SNAPSHOT guava-io diff --git a/guava/pom.xml b/guava/pom.xml index 3a19901a02..4ca9918455 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung guava 0.1.0-SNAPSHOT guava @@ -26,8 +25,6 @@ ${assertj.version} test - - @@ -41,9 +38,6 @@ - - 24.0-jre - 3.6.1 diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml index 705792ad05..9e0b0671d0 100644 --- a/hazelcast/pom.xml +++ b/hazelcast/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung hazelcast 0.0.1-SNAPSHOT hazelcast diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index b2b0f98dd1..183c4438de 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung httpclient-simple 0.1-SNAPSHOT httpclient-simple diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 8cd483cfc6..6316ee4eed 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung httpclient 0.1-SNAPSHOT httpclient @@ -48,11 +47,6 @@ httpmime ${httpclient.version} - - commons-codec - commons-codec - ${commons-codec.version} - org.apache.httpcomponents httpasyncclient @@ -82,51 +76,12 @@ - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*LiveTest.java - - - - - - - json - - - - - - - - - 19.0 - 1.10 4.1.4 2.5.1 4.5.8 - - 1.6.1 \ No newline at end of file diff --git a/hystrix/pom.xml b/hystrix/pom.xml index e08af2c40f..4aeb47f095 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -41,23 +41,11 @@ hystrix-metrics-event-stream ${hystrix-metrics-event-stream.version} - com.netflix.rxjava rxjava-core ${rxjava-core.version} - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - - - org.springframework - spring-test - test - @@ -65,9 +53,7 @@ 1.5.8 0.20.7 - 2.7 1.5.8 - 1.5.8 diff --git a/jackson-simple/README.md b/jackson-simple/README.md index 302fcb5b05..9d24a20e4a 100644 --- a/jackson-simple/README.md +++ b/jackson-simple/README.md @@ -2,7 +2,8 @@ This module contains articles about Jackson that are also part of the Jackson Ebook. -###The Course +### The Course + The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java index 2745e4f767..a339ddf2c5 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java @@ -1,20 +1,29 @@ package com.baeldung.jackson.objectmapper; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.net.URL; +import java.util.List; +import java.util.Map; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + import com.baeldung.jackson.objectmapper.dto.Car; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.List; -import java.util.Map; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; public class JavaReadWriteJsonExampleUnitTest { + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; final String LOCAL_JSON = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]"; @@ -27,6 +36,19 @@ public class JavaReadWriteJsonExampleUnitTest { assertThat(carAsString, containsString("renault")); } + @Test + public void whenWriteToFile_thanCorrect() throws Exception { + File resultFile = folder.newFile("car.json"); + + ObjectMapper objectMapper = new ObjectMapper(); + Car car = new Car("yellow", "renault"); + objectMapper.writeValue(resultFile, car); + + Car fromFile = objectMapper.readValue(resultFile, Car.class); + assertEquals(car.getType(), fromFile.getType()); + assertEquals(car.getColor(), fromFile.getColor()); + } + @Test public void whenReadJsonToJava_thanCorrect() throws Exception { final ObjectMapper objectMapper = new ObjectMapper(); @@ -66,4 +88,26 @@ public class JavaReadWriteJsonExampleUnitTest { assertNotNull(key); } } + + @Test + public void wheReadFromFile_thanCorrect() throws Exception { + File resource = new File("src/test/resources/json_car.json"); + + ObjectMapper objectMapper = new ObjectMapper(); + Car fromFile = objectMapper.readValue(resource, Car.class); + + assertEquals("BMW", fromFile.getType()); + assertEquals("Black", fromFile.getColor()); + } + + @Test + public void wheReadFromUrl_thanCorrect() throws Exception { + URL resource = new URL("file:src/test/resources/json_car.json"); + + ObjectMapper objectMapper = new ObjectMapper(); + Car fromFile = objectMapper.readValue(resource, Car.class); + + assertEquals("BMW", fromFile.getType()); + assertEquals("Black", fromFile.getColor()); + } } diff --git a/jackson-simple/src/test/resources/json_car.json b/jackson-simple/src/test/resources/json_car.json new file mode 100644 index 0000000000..2f6b35b523 --- /dev/null +++ b/jackson-simple/src/test/resources/json_car.json @@ -0,0 +1,4 @@ +{ + "color": "Black", + "type": "BMW" +} \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/City.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/City.java new file mode 100644 index 0000000000..2bbef534c3 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/City.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.deserialization.enums; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java new file mode 100644 index 0000000000..2c96b6eb80 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/Distance.java @@ -0,0 +1,31 @@ +package com.baeldung.jackson.deserialization.enums; + +public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public void setMeters(double meters) { + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } +} + diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/City.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/City.java new file mode 100644 index 0000000000..36ef7e244a --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/City.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.deserialization.enums.customdeserializer; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java new file mode 100644 index 0000000000..bae0c0df34 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/CustomEnumDeserializer.java @@ -0,0 +1,42 @@ +package com.baeldung.jackson.deserialization.enums.customdeserializer; + +import java.io.IOException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; + +public class CustomEnumDeserializer extends StdDeserializer { + + private static final long serialVersionUID = -1166032307856492833L; + + public CustomEnumDeserializer() { + this(null); + } + + public CustomEnumDeserializer(Class c) { + super(c); + } + + @Override + public Distance deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { + + JsonNode node = jsonParser.getCodec().readTree(jsonParser); + + String unit = node.get("unit").asText(); + double meters = node.get("meters").asDouble(); + + for (Distance distance : Distance.values()) { + + if (distance.getUnit().equals(unit) && + Double.compare(distance.getMeters(), meters) == 0) { + + return distance; + } + } + + return null; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java new file mode 100644 index 0000000000..9cb3a0c391 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/customdeserializer/Distance.java @@ -0,0 +1,33 @@ +package com.baeldung.jackson.deserialization.enums.customdeserializer; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +@JsonDeserialize(using = CustomEnumDeserializer.class) +public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public void setMeters(double meters) { + this.meters = meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } +} \ No newline at end of file diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/City.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/City.java new file mode 100644 index 0000000000..6a478dd263 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/City.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.deserialization.enums.jsoncreator; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java new file mode 100644 index 0000000000..18235fb5c6 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsoncreator/Distance.java @@ -0,0 +1,48 @@ +package com.baeldung.jackson.deserialization.enums.jsoncreator; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public void setMeters(double meters) { + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + @JsonCreator + public static Distance forValues(@JsonProperty("unit") String unit, @JsonProperty("meters") double meters) { + + for (Distance distance : Distance.values()) { + if (distance.unit.equals(unit) && Double.compare(distance.meters, meters) == 0) { + + return distance; + } + } + + return null; + + } +} + diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/City.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/City.java new file mode 100644 index 0000000000..7f763f97c4 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/City.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.deserialization.enums.jsonproperty; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java new file mode 100644 index 0000000000..e671a9ae5b --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonproperty/Distance.java @@ -0,0 +1,51 @@ +package com.baeldung.jackson.deserialization.enums.jsonproperty; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public enum Distance { + + @JsonProperty("distance-in-km") + KILOMETER("km", 1000), + + @JsonProperty("distance-in-miles") + MILE("miles", 1609.34), + + @JsonProperty("distance-in-meters") + METER("meters", 1), + + @JsonProperty("distance-in-inches") + INCH("inches", 0.0254), + + @JsonProperty("distance-in-cm") + CENTIMETER("cm", 0.01), + + @JsonProperty("distance-in-mm") + MILLIMETER("mm", 0.001); + + private String unit; + private double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public void setMeters(double meters) { + this.meters = meters; + } + + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + +} + + diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/City.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/City.java new file mode 100644 index 0000000000..014668ea8c --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/City.java @@ -0,0 +1,15 @@ +package com.baeldung.jackson.deserialization.enums.jsonvalue; + +public class City { + + private Distance distance; + + public Distance getDistance() { + return distance; + } + + public void setDistance(Distance distance) { + this.distance = distance; + } + +} diff --git a/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java new file mode 100644 index 0000000000..44bb5f20c3 --- /dev/null +++ b/jackson/src/main/java/com/baeldung/jackson/deserialization/enums/jsonvalue/Distance.java @@ -0,0 +1,35 @@ +package com.baeldung.jackson.deserialization.enums.jsonvalue; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum Distance { + + KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); + + private String unit; + private double meters; + + private Distance(String unit, double meters) { + this.unit = unit; + this.meters = meters; + } + + public void setMeters(double meters) { + this.meters = meters; + } + + @JsonValue + public double getMeters() { + return meters; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + +} + diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultEnumDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultEnumDeserializationUnitTest.java new file mode 100644 index 0000000000..c7ce96e013 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/DefaultEnumDeserializationUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.jackson.deserialization.enums; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.IOException; +import org.junit.Test; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class DefaultEnumDeserializationUnitTest { + + @Test + public void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\":\"KILOMETER\"}"; + City city = new ObjectMapper().readValue(json, City.class); + + assertEquals(Distance.KILOMETER, city.getDistance()); + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/EnumCustomDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/EnumCustomDeserializationUnitTest.java new file mode 100644 index 0000000000..e8dbfa8df8 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/customdeserializer/EnumCustomDeserializationUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.jackson.deserialization.enums.customdeserializer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.IOException; +import org.junit.Test; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class EnumCustomDeserializationUnitTest { + + @Test + public void givenEnumWithCustomDeserializer_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; + + City city = new ObjectMapper().readValue(json, City.class); + assertEquals(Distance.MILE, city.getDistance()); + } +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java new file mode 100644 index 0000000000..d778cbe26b --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.jackson.deserialization.enums.jsoncreator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.IOException; +import org.junit.Test; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class EnumDeserializationUsingJsonCreatorUnitTest { + + @Test + public void givenEnumWithJsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; + + City city = new ObjectMapper().readValue(json, City.class); + assertEquals(Distance.MILE, city.getDistance()); + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java new file mode 100644 index 0000000000..134f4a29cc --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.jackson.deserialization.enums.jsonproperty; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.IOException; +import org.junit.Test; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class EnumDeserializationUsingJsonPropertyUnitTest { + + @Test + public void givenEnumWithJsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": \"distance-in-km\"}"; + + City city = new ObjectMapper().readValue(json, City.class); + assertEquals(Distance.KILOMETER, city.getDistance()); + + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java new file mode 100644 index 0000000000..85afcb9a69 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/deserialization/enums/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.jackson.deserialization.enums.jsonvalue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.IOException; +import org.junit.Test; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class EnumDeserializationUsingJsonValueUnitTest { + + @Test + public void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { + String json = "{\"distance\": \"0.0254\"}"; + + City city = new ObjectMapper().readValue(json, City.class); + assertEquals(Distance.INCH, city.getDistance()); + } + +} diff --git a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java index 45c0ba1382..d4fb2401ed 100644 --- a/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/enums/JacksonEnumSerializationUnitTest.java @@ -2,11 +2,8 @@ package com.baeldung.jackson.enums; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; - import java.io.IOException; - import org.junit.Test; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -18,5 +15,5 @@ public class JacksonEnumSerializationUnitTest { assertThat(dtoAsString, containsString("1609.34")); } - + } diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml index 2f9e011aa7..4c5d0f31d5 100644 --- a/java-blockchain/pom.xml +++ b/java-blockchain/pom.xml @@ -7,12 +7,14 @@ 0.1.0-SNAPSHOT java-blockchain jar + com.baeldung parent-java 0.0.1-SNAPSHOT ../parent-java + java-blockchain @@ -33,8 +35,10 @@ + 1.8 1.8 + \ No newline at end of file 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/.gitignore b/java-dates-2/.gitignore deleted file mode 100644 index 6471aabbcf..0000000000 --- a/java-dates-2/.gitignore +++ /dev/null @@ -1,29 +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 - -#jenv -.java-version \ No newline at end of file diff --git a/java-dates-2/README.md b/java-dates-2/README.md deleted file mode 100644 index b2f8319e58..0000000000 --- a/java-dates-2/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## Relevant Articles: -- [Converting Between LocalDate and XMLGregorianCalendar](https://www.baeldung.com/java-localdate-to-xmlgregoriancalendar) -- [Convert Time to Milliseconds in Java](https://www.baeldung.com/java-time-milliseconds) -- [Check If a String Is a Valid Date in Java](https://www.baeldung.com/java-string-valid-date) 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 2c962ece64..0000000000 --- a/java-dates/README.md +++ /dev/null @@ -1,33 +0,0 @@ -========= - -## Java Dates Cookbooks and Examples - -### Relevant Articles: -- [TemporalAdjuster in Java](https://www.baeldung.com/java-temporal-adjuster) -- [Handling Daylight Savings Time in Java](https://www.baeldung.com/java-daylight-savings) -- [Period and Duration in Java](https://www.baeldung.com/java-period-duration) -- [Difference Between Two Dates in Java](https://www.baeldung.com/java-date-difference) -- [RegEx for matching Date Pattern in Java](https://www.baeldung.com/java-date-regular-expressions) -- [Migrating to the New Java 8 Date Time API](https://www.baeldung.com/migrating-to-java-8-date-time-api) -- [Introduction to the Java 8 Date/Time API](https://www.baeldung.com/java-8-date-time-intro) -- [Get the Current Date, Time and Timestamp in Java 8](https://www.baeldung.com/current-date-time-and-timestamp-in-java-8) -- [Get Date Without Time in Java](https://www.baeldung.com/java-date-without-time) -- [How to Get All Dates Between Two Dates?](https://www.baeldung.com/java-between-dates) -- [Convert Date to LocalDate or LocalDateTime and Back](https://www.baeldung.com/java-date-to-localdate-and-localdatetime) -- [Display All Time Zones With GMT And UTC in Java](https://www.baeldung.com/java-time-zones) -- [Extracting Year, Month and Day from Date in Java](https://www.baeldung.com/java-year-month-day) -- [Guide to java.util.GregorianCalendar](https://www.baeldung.com/java-gregorian-calendar) -- [Measure Elapsed Time in Java](https://www.baeldung.com/java-measure-elapsed-time) -- [How to Get the Start and the End of a Day using Java](https://www.baeldung.com/java-day-start-end) -- [Calculate Age in Java](https://www.baeldung.com/java-get-age) -- [Increment Date in Java](https://www.baeldung.com/java-increment-date) -- [Add Hours To a Date In Java](https://www.baeldung.com/java-add-hours-date) -- [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter) -- [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string) -- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp) -- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp) -- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format) -- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) -- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) -- [Introduction to Joda-Time](https://www.baeldung.com/joda-time) -- [Convert String to Date in Java](https://www.baeldung.com/java-string-to-date) 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/main/java/com/baeldung/datetime/UseDateTimeFormatter.java b/java-dates/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java new file mode 100644 index 0000000000..13a2ba6a1a --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.Locale; + +public class UseDateTimeFormatter { + public String formatAsIsoDate(LocalDateTime localDateTime) { + return localDateTime.format(DateTimeFormatter.ISO_DATE); + } + + public String formatCustom(LocalDateTime localDateTime, String pattern) { + return localDateTime.format(DateTimeFormatter.ofPattern(pattern)); + } + + public String formatWithStyleAndLocale(LocalDateTime localDateTime, FormatStyle formatStyle, Locale locale) { + return localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(formatStyle) + .withLocale(locale)); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java b/java-dates/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java new file mode 100644 index 0000000000..ed8499d6e0 --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java @@ -0,0 +1,11 @@ +package com.baeldung.datetime; + +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +public class UseOffsetDateTime { + public OffsetDateTime offsetOfLocalDateTimeAndOffset(LocalDateTime localDateTime, ZoneOffset offset) { + return OffsetDateTime.of(localDateTime, offset); + } +} diff --git a/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java b/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java deleted file mode 100644 index db6b353ba6..0000000000 --- a/java-dates/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.dateapi; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.time.Duration; -import java.time.Instant; -import java.time.temporal.ChronoUnit; - -import org.junit.Test; - -public class JavaDurationUnitTest { - - @Test - public void test2() { - Instant start = Instant.parse("2017-10-03T10:15:30.00Z"); - Instant end = Instant.parse("2017-10-03T10:16:30.00Z"); - - Duration duration = Duration.between(start, end); - - assertFalse(duration.isNegative()); - - assertEquals(60, duration.getSeconds()); - assertEquals(1, duration.toMinutes()); - - Duration fromDays = Duration.ofDays(1); - assertEquals(86400, fromDays.getSeconds()); - - Duration fromMinutes = Duration.ofMinutes(60); - assertEquals(1, fromMinutes.toHours()); - - assertEquals(120, duration.plusSeconds(60).getSeconds()); - assertEquals(30, duration.minusSeconds(30).getSeconds()); - - assertEquals(120, duration.plus(60, ChronoUnit.SECONDS).getSeconds()); - assertEquals(30, duration.minus(30, ChronoUnit.SECONDS).getSeconds()); - - Duration fromChar1 = Duration.parse("P1DT1H10M10.5S"); - Duration fromChar2 = Duration.parse("PT10M"); - } - -} diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java new file mode 100644 index 0000000000..797e0b954a --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.time.Month; +import java.time.format.FormatStyle; +import java.util.Locale; + +import org.junit.Test; + +public class UseDateTimeFormatterUnitTest { + private final UseDateTimeFormatter subject = new UseDateTimeFormatter(); + private final LocalDateTime localDateTime = LocalDateTime.of(2015, Month.JANUARY, 25, 6, 30); + + @Test + public void givenALocalDate_whenFormattingAsIso_thenPass() { + String result = subject.formatAsIsoDate(localDateTime); + + assertThat(result).isEqualTo("2015-01-25"); + } + + @Test + public void givenALocalDate_whenFormattingWithPattern_thenPass() { + String result = subject.formatCustom(localDateTime, "yyyy/MM/dd"); + + assertThat(result).isEqualTo("2015/01/25"); + } + + @Test + public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() { + String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK); + + assertThat(result).isEqualTo("25 Jan 2015, 06:30:00"); + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java new file mode 100644 index 0000000000..5b58dd3848 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.time.Month; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +import org.junit.Test; + +public class UseOffsetDateTimeUnitTest { + private final UseOffsetDateTime subject = new UseOffsetDateTime(); + + @Test + public void givenAZoneOffSetAndLocalDateTime_whenCombing_thenValidResult() { + ZoneOffset offset = ZoneOffset.of("+02:00"); + LocalDateTime localDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 6, 30); + + OffsetDateTime result = subject.offsetOfLocalDateTimeAndOffset(localDateTime, offset); + + assertThat(result.toString()).isEqualTo("2015-02-20T06:30+02:00"); + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java new file mode 100644 index 0000000000..78d9a647fe --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.junit.Test; + +public class UseToInstantUnitTest { + + private UseToInstant subject = new UseToInstant(); + + @Test + public void givenAGregorianCalenderDate_whenConvertingToLocalDate_thenAsExpected() { + GregorianCalendar givenCalender = new GregorianCalendar(2018, Calendar.JULY, 28); + + LocalDateTime localDateTime = subject.convertDateToLocalDate(givenCalender); + + assertThat(localDateTime).isEqualTo("2018-07-28T00:00:00"); + } + + @Test + public void givenADate_whenConvertingToLocalDate_thenAsExpected() { + Date givenDate = new Date(1465817690000L); + + LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate); + + assertThat(localDateTime).isEqualTo("2016-06-13T13:34:50"); + } +} \ No newline at end of file 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-math/README.md b/java-math/README.md index 49ff5afde1..d80a07258a 100644 --- a/java-math/README.md +++ b/java-math/README.md @@ -14,3 +14,5 @@ This module contains articles about math in Java. - [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) - [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging) - [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication) +- [Calculating Logarithms in Java](https://www.baeldung.com/java-logarithms) +- [Finding Greatest Common Divisor in Java](https://www.baeldung.com/java-greatest-common-divisor) diff --git a/java-numbers-2/README.md b/java-numbers-2/README.md index 48f9acd32d..e200c4aa03 100644 --- a/java-numbers-2/README.md +++ b/java-numbers-2/README.md @@ -13,4 +13,6 @@ This module contains articles about numbers in Java. - [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers) - [Finding the Least Common Multiple in Java](https://www.baeldung.com/java-least-common-multiple) - [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers) +- [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers) +- [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range) - More articles: [[<-- prev]](/../java-numbers) 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/.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/entities/User.java b/java-streams/src/main/java/com/baeldung/reduce/entities/User.java deleted file mode 100644 index a17c6a02b6..0000000000 --- a/java-streams/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/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 index 9865019f74..ecbdb7def9 100644 --- a/java-strings-2/README.md +++ b/java-strings-2/README.md @@ -5,26 +5,7 @@ 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) -- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) -- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) -- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) -- [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) -- [Guide to java.util.Formatter](https://www.baeldung.com/java-string-formatter) -- [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) -- [Guide to StreamTokenizer](https://www.baeldung.com/java-streamtokenizer) -- More articles: [[<-- prev>]](/java-strings) [[next -->]](/java-strings-3) +- More articles: [[<-- prev>]](/java-strings) 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 index 3b00cd11ed..4c618585f3 100644 --- a/java-strings-ops/README.md +++ b/java-strings-ops/README.md @@ -3,16 +3,4 @@ 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) -- [CharSequence vs. String in Java](https://www.baeldung.com/java-char-sequence-string) -- [StringBuilder and StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer) diff --git a/java-strings-ops/pom.xml b/java-strings-ops/pom.xml index b6a7ea2728..ebed216c2b 100644 --- a/java-strings-ops/pom.xml +++ b/java-strings-ops/pom.xml @@ -90,9 +90,9 @@ 3.8.1 + 27.0.1-jre 3.6.1 - 27.0.1-jre 5.3.1 diff --git a/java-strings-ops/src/main/resources/log4j.properties b/java-strings-ops/src/main/resources/log4j.properties new file mode 100644 index 0000000000..2ea9fa9209 --- /dev/null +++ b/java-strings-ops/src/main/resources/log4j.properties @@ -0,0 +1,8 @@ +# Root logger option +log4j.rootLogger=DEBUG, stdout + +# Redirect log messages to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java deleted file mode 100644 index 6157640a4a..0000000000 --- a/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.string; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.junit.jupiter.api.Test; - -import com.google.common.base.Splitter; - -public class SplitUnitTest { - - @Test - public void givenString_whenSplit_thenReturnsArray_through_JavaLangString() { - assertThat("peter,james,thomas".split(",")) - .containsExactly("peter", "james", "thomas"); - - assertThat("car jeep scooter".split(" ")) - .containsExactly("car", "jeep", "scooter"); - - assertThat("1-120-232323".split("-")) - .containsExactly("1", "120", "232323"); - - assertThat("192.168.1.178".split("\\.")) - .containsExactly("192", "168", "1", "178"); - - assertThat("b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*")) - .containsExactly("b", "a", "e", "l", "d", "u", "n", "g"); - } - - @Test - public void givenString_whenSplit_thenReturnsArray_through_StringUtils() { - StringUtils.split("car jeep scooter"); - - assertThat(StringUtils.split("car jeep scooter")) - .containsExactly("car", "jeep", "scooter"); - - assertThat(StringUtils.split("car jeep scooter")) - .containsExactly("car", "jeep", "scooter"); - - assertThat(StringUtils.split("car:jeep:scooter", ":")) - .containsExactly("car", "jeep", "scooter"); - - assertThat(StringUtils.split("car.jeep.scooter", ".")) - .containsExactly("car", "jeep", "scooter"); - } - - @Test - public void givenString_whenSplit_thenReturnsList_Splitter() { - //given - List resultList = Splitter.on(',').trimResults().omitEmptyStrings().splitToList("car,jeep,, scooter"); - - assertThat(resultList) - .containsExactly("car", "jeep", "scooter"); - } - - @Test - public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_Regex() { - assertThat(" car , jeep, scooter ".trim() - .split("\\s*,\\s*")).containsExactly("car", "jeep", "scooter"); - - } - - @Test - public void givenStringContainsSpaces_whenSplitAndTrim_thenReturnsArray_using_java_8() { - assertThat(Arrays.stream(" car , jeep, scooter ".split(",")) - .map(String::trim) - .toArray(String[]::new)).containsExactly("car", "jeep", "scooter"); - } -} diff --git a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java deleted file mode 100644 index 9a88416179..0000000000 --- a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.string.tostring; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -public class CustomerArrayToStringUnitTest { - private static final String CUSTOMER_ARRAY_TO_STRING - = "Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], getFirstName()=Rajesh, getLastName()=Bhojwani]"; - - @Test - public void givenArray_whenToString_thenCustomerDetails() { - CustomerArrayToString customer = new CustomerArrayToString(); - customer.setFirstName("Rajesh"); - customer.setLastName("Bhojwani"); - Order[] orders = new Order[1]; - orders[0] = new Order(); - orders[0].setOrderId("A1111"); - orders[0].setDesc("Game"); - orders[0].setStatus("In-Shiping"); - customer.setOrders(orders); - - assertEquals(CUSTOMER_ARRAY_TO_STRING, customer.toString()); - } - -} diff --git a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java deleted file mode 100644 index e04512ff75..0000000000 --- a/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.string.tostring; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.jupiter.api.Test; - -public class CustomerWrapperCollectionToStringUnitTest { - private static final String CUSTOMER_WRAPPER_COLLECTION_TO_STRING - = "Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, getLastName()=Bhojwani]"; - - @Test - public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() { - CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString(); - customer.setFirstName("Rajesh"); - customer.setLastName("Bhojwani"); - customer.setScore(8); - - List orders = new ArrayList(); - orders.add("Book"); - orders.add("Pen"); - customer.setOrders(orders); - - StringBuffer fullname = new StringBuffer(); - fullname.append(customer.getLastName()+", "+ customer.getFirstName()); - customer.setFullname(fullname); - - assertEquals(CUSTOMER_WRAPPER_COLLECTION_TO_STRING, customer.toString()); - } - -} diff --git a/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java index 4bbf63f87e..ca56d5aab5 100644 --- a/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java +++ b/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java @@ -1,7 +1,8 @@ package com.baeldung.stringpool; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; -import static org.assertj.core.api.Assertions.*; public class StringPoolUnitTest { diff --git a/java-strings/README.md b/java-strings/README.md index 3146b54fa8..4668ad014e 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -3,17 +3,8 @@ This module contains articles about strings in Java. ### Relevant Articles: -- [String Operations with Java Streams](https://www.baeldung.com/java-stream-operations-on-strings) -- [Java 8 StringJoiner](https://www.baeldung.com/java-string-joiner) -- [Quick Guide to the Java StringTokenizer](https://www.baeldung.com/java-stringtokenizer) - [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) -- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) - [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/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 aca078af15..a471ccd39d 100644 --- a/jaxb/README.md +++ b/jaxb/README.md @@ -4,3 +4,4 @@ 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 09de7051ca..366e7665f3 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -9,3 +9,4 @@ This module contains articles about Jersey. - [Set a Response Body in JAX-RS](https://www.baeldung.com/jax-rs-response) - [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/jhipster-5/bookstore-monolith/README.md b/jhipster-5/bookstore-monolith/README.md index 0537f5b1a5..e4e69b83ac 100644 --- a/jhipster-5/bookstore-monolith/README.md +++ b/jhipster-5/bookstore-monolith/README.md @@ -1,3 +1,5 @@ ## Relevant articles: - [Creating New APIs and Views in JHipster](https://www.baeldung.com/jhipster-new-apis-and-views) +- [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/kotlin-libraries-2/README.md b/kotlin-libraries-2/README.md index 188f99dc16..4064ef67d8 100644 --- a/kotlin-libraries-2/README.md +++ b/kotlin-libraries-2/README.md @@ -6,4 +6,6 @@ This module contains articles about Kotlin Libraries. - [Jackson Support for Kotlin](https://www.baeldung.com/jackson-kotlin) - [Introduction to RxKotlin](https://www.baeldung.com/rxkotlin) +- [MockK: A Mocking Library for Kotlin](https://www.baeldung.com/kotlin-mockk) +- [Kotlin Immutable Collections](https://www.baeldung.com/kotlin-immutable-collections) - More articles: [[<-- prev]](/kotlin-libraries) diff --git a/kotlin-libraries-2/pom.xml b/kotlin-libraries-2/pom.xml index 14ac61a093..518142403e 100644 --- a/kotlin-libraries-2/pom.xml +++ b/kotlin-libraries-2/pom.xml @@ -28,9 +28,30 @@ junit test + + com.google.guava + guava + ${guava.version} + + + + org.jetbrains.kotlinx + kotlinx-collections-immutable + ${kotlinx-collections-immutable.version} + + + + io.mockk + mockk + ${mockk.version} + test + + 27.1-jre + 1.9.3 + 0.1 diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt similarity index 100% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt similarity index 100% rename from kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt similarity index 100% rename from kotlin-libraries/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt similarity index 100% rename from kotlin-libraries/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt similarity index 100% rename from kotlin-libraries/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/mockk/TestableService.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/TestableService.kt similarity index 100% rename from kotlin-libraries/src/test/kotlin/com/baeldung/mockk/TestableService.kt rename to kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/TestableService.kt diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md index e4b0a35d28..99a57c8293 100644 --- a/kotlin-libraries/README.md +++ b/kotlin-libraries/README.md @@ -14,6 +14,4 @@ This module contains articles about Kotlin Libraries. - [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow) - [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) - [REST API With Kotlin and Kovert](https://www.baeldung.com/kotlin-kovert) -- [MockK: A Mocking Library for Kotlin](https://www.baeldung.com/kotlin-mockk) -- [Kotlin Immutable Collections](https://www.baeldung.com/kotlin-immutable-collections) - More articles: [[next -->]](/kotlin-libraries-2) diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index 5299b5029e..7099166674 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -129,25 +129,7 @@ test - - com.google.guava - guava - ${guava.version} - - - - org.jetbrains.kotlinx - kotlinx-collections-immutable - ${kotlinx-collections-immutable.version} - - - - io.mockk - mockk - ${mockk.version} - test - net.bytebuddy byte-buddy @@ -185,13 +167,10 @@ 5.2.0 3.10.0 0.10.4 - 1.9.3 - 27.1-jre 3.3.0 1.8.13 2.6 2.3.0 - 0.1 0.7.3 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-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 f27fb73dd6..9cb89f3552 100644 --- a/libraries-primitive/README.MD +++ b/libraries-primitive/README.MD @@ -1,3 +1,4 @@ ### Relevant Articles - [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/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/mapstruct/README.md b/mapstruct/README.md index b784820b98..f5a1e1a092 100644 --- a/mapstruct/README.md +++ b/mapstruct/README.md @@ -4,3 +4,6 @@ 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 f27f5fb795..6050b2b310 100644 --- a/metrics/README.md +++ b/metrics/README.md @@ -7,3 +7,4 @@ This module contains articles about metrics. - [Intro to Dropwizard Metrics](https://www.baeldung.com/dropwizard-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/src/main/java/com/baeldung/prototype/Position.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Position.java new file mode 100644 index 0000000000..dd7694feb6 --- /dev/null +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Position.java @@ -0,0 +1,51 @@ +package com.baeldung.prototype; + +public final class Position { + + private final int x; + private final int y; + + public Position(int x, int y) { + this.x = x; + this.y = y; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + x; + result = prime * result + y; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Position other = (Position) obj; + if (x != other.x) + return false; + if (y != other.y) + return false; + return true; + } + + @Override + public String toString() { + return "Position [x=" + x + ", y=" + y + "]"; + } + +} diff --git a/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java new file mode 100644 index 0000000000..f95d568647 --- /dev/null +++ b/patterns/design-patterns-creational/src/main/java/com/baeldung/prototype/Tree.java @@ -0,0 +1,54 @@ +package com.baeldung.prototype; + +public class Tree implements Cloneable { + + private double mass; + private double height; + private Position position; + + public Tree(double mass, double height) { + this.mass = mass; + this.height = height; + } + + public void setMass(double mass) { + this.mass = mass; + } + + public void setHeight(double height) { + this.height = height; + } + + public void setPosition(Position position) { + this.position = position; + } + + public double getMass() { + return mass; + } + + public double getHeight() { + return height; + } + + public Position getPosition() { + return position; + } + + @Override + public Tree clone() { + Tree tree = null; + try { + tree = (Tree) super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return tree; + } + + @Override + public String toString() { + return "Tree [mass=" + mass + ", height=" + height + ", position=" + position + "]"; + } + +} diff --git a/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java b/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java new file mode 100644 index 0000000000..0d06da53d6 --- /dev/null +++ b/patterns/design-patterns-creational/src/test/java/com/baeldung/prototype/TreePrototypeUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.prototype; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class TreePrototypeUnitTest { + + @Test + public void givenATreePrototypeWhenClonedThenCreateA_Clone() { + double mass = 10.0; + double height = 3.7; + Position position = new Position(3, 7); + Position otherPosition = new Position(4, 8); + + Tree tree = new Tree(mass, height); + tree.setPosition(position); + Tree anotherTree = tree.clone(); + anotherTree.setPosition(otherPosition); + + assertEquals(position, tree.getPosition()); + assertEquals(otherPosition, anotherTree.getPosition()); + } +} 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/hibernate5-2/pom.xml similarity index 63% rename from persistence-modules/hibernate-parameters/pom.xml rename to persistence-modules/hibernate5-2/pom.xml index b744e181da..ef091c331e 100644 --- a/persistence-modules/hibernate-parameters/pom.xml +++ b/persistence-modules/hibernate5-2/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - hibernate-parameters + hibernate5-2 0.1-SNAPSHOT - hibernate-parameters + hibernate5-2 jar Hibernate tutorial illustrating the use of named parameters @@ -20,31 +20,16 @@ org.hibernate hibernate-core - 5.4.4.Final + 5.4.7.Final com.h2database h2 - 1.4.196 + 1.4.200 - - - - false - src/test/java - - **/*.xml - - - - src/test/resources - - - - true diff --git a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.java b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java similarity index 90% rename from persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.java rename to persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java index f44b1bfd8a..7912659a09 100644 --- a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.java +++ b/persistence-modules/hibernate5-2/src/main/java/com/baeldung/hibernateparameters/Event.java @@ -1,4 +1,4 @@ -package com.baeldung.hibernate_parameters; +package com.baeldung.hibernateparameters; public class Event { private Long id; diff --git a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.hbm.xml b/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml similarity index 85% rename from persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.hbm.xml rename to persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml index 4055718776..c485080879 100644 --- a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/Event.hbm.xml +++ b/persistence-modules/hibernate5-2/src/main/resources/com/baeldung/hibernateparameters/Event.hbm.xml @@ -3,7 +3,7 @@ "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> - + diff --git a/persistence-modules/hibernate-parameters/src/test/resources/hibernate.cfg.xml b/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml similarity index 89% rename from persistence-modules/hibernate-parameters/src/test/resources/hibernate.cfg.xml rename to persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml index 480baae4c1..be564aaf5a 100644 --- a/persistence-modules/hibernate-parameters/src/test/resources/hibernate.cfg.xml +++ b/persistence-modules/hibernate5-2/src/main/resources/hibernate.cfg.xml @@ -7,7 +7,7 @@ org.h2.Driver - jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE + jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1 sa @@ -21,7 +21,7 @@ create - + diff --git a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/NamedParameterUnitTest.java b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java similarity index 97% rename from persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/NamedParameterUnitTest.java rename to persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java index 23854dc393..4efa1e1f68 100644 --- a/persistence-modules/hibernate-parameters/src/test/java/com/baeldung/hibernate_parameters/NamedParameterUnitTest.java +++ b/persistence-modules/hibernate5-2/src/test/java/com/baeldung/hibernateparameters/NamedParameterUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.hibernate_parameters; +package com.baeldung.hibernateparameters; import org.hibernate.Session; import org.hibernate.SessionFactory; @@ -30,6 +30,7 @@ public class NamedParameterUnitTest { session.getTransaction().commit(); session.close(); } catch (Exception e) { + fail(e); StandardServiceRegistryBuilder.destroy(registry); } } 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/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index 790c4a07df..2488c5ccdf 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -1,5 +1,4 @@ - 4.0.0 java-jpa-2 @@ -49,6 +48,13 @@ ${postgres.version} runtime + + + org.assertj + assertj-core + ${assertj.version} + test + @@ -108,6 +114,7 @@ 2.7.4-RC1 42.2.5 2.2 + 3.11.1 \ No newline at end of file diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java new file mode 100644 index 0000000000..e5e228d013 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/AllergensAsEntity.java @@ -0,0 +1,73 @@ +package com.baeldung.jpa.multipletables.multipleentities; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; + +import com.baeldung.jpa.multipletables.secondarytable.MealAsSingleEntity; + +@Entity +@Table(name = "allergens") +public class AllergensAsEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "meal_id") + private Long mealId; + + @OneToOne + @PrimaryKeyJoinColumn(name = "meal_id") + private MealAsSingleEntity meal; + + @Column(name = "peanuts") + private boolean peanuts; + + @Column(name = "celery") + private boolean celery; + + @Column(name = "sesame_seeds") + private boolean sesameSeeds; + + public MealAsSingleEntity getMeal() { + return meal; + } + + public void setMeal(MealAsSingleEntity meal) { + this.meal = meal; + } + + public boolean isPeanuts() { + return peanuts; + } + + public void setPeanuts(boolean peanuts) { + this.peanuts = peanuts; + } + + public boolean isCelery() { + return celery; + } + + public void setCelery(boolean celery) { + this.celery = celery; + } + + public boolean isSesameSeeds() { + return sesameSeeds; + } + + public void setSesameSeeds(boolean sesameSeeds) { + this.sesameSeeds = sesameSeeds; + } + + @Override + public String toString() { + return "AllergensAsEntity [peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java new file mode 100644 index 0000000000..74105f8f1f --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/multipleentities/MealWithMultipleEntities.java @@ -0,0 +1,75 @@ +package com.baeldung.jpa.multipletables.multipleentities; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "meal") +public class MealWithMultipleEntities { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "price") + private BigDecimal price; + + @OneToOne(mappedBy = "meal") + private AllergensAsEntity allergens; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public AllergensAsEntity getAllergens() { + return allergens; + } + + public void setAllergens(AllergensAsEntity allergens) { + this.allergens = allergens; + } + + public Long getId() { + return id; + } + + @Override + public String toString() { + return "MealWithMultipleEntities [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", allergens=" + allergens + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java new file mode 100644 index 0000000000..2929f391a4 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/MealAsSingleEntity.java @@ -0,0 +1,99 @@ +package com.baeldung.jpa.multipletables.secondarytable; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.Table; + +@Entity +@Table(name = "meal") +@SecondaryTable(name = "allergens", pkJoinColumns = @PrimaryKeyJoinColumn(name = "meal_id")) +public class MealAsSingleEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "price") + private BigDecimal price; + + @Column(name = "peanuts", table = "allergens") + private boolean peanuts; + + @Column(name = "celery", table = "allergens") + private boolean celery; + + @Column(name = "sesame_seeds", table = "allergens") + private boolean sesameSeeds; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public boolean isPeanuts() { + return peanuts; + } + + public void setPeanuts(boolean peanuts) { + this.peanuts = peanuts; + } + + public boolean isCelery() { + return celery; + } + + public void setCelery(boolean celery) { + this.celery = celery; + } + + public boolean isSesameSeeds() { + return sesameSeeds; + } + + public void setSesameSeeds(boolean sesameSeeds) { + this.sesameSeeds = sesameSeeds; + } + + public Long getId() { + return id; + } + + @Override + public String toString() { + return "MealAsSingleEntity [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java new file mode 100644 index 0000000000..1c1f05890b --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/AllergensAsEmbeddable.java @@ -0,0 +1,47 @@ +package com.baeldung.jpa.multipletables.secondarytable.embeddable; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +public class AllergensAsEmbeddable { + + @Column(name = "peanuts", table = "allergens") + private boolean peanuts; + + @Column(name = "celery", table = "allergens") + private boolean celery; + + @Column(name = "sesame_seeds", table = "allergens") + private boolean sesameSeeds; + + public boolean isPeanuts() { + return peanuts; + } + + public void setPeanuts(boolean peanuts) { + this.peanuts = peanuts; + } + + public boolean isCelery() { + return celery; + } + + public void setCelery(boolean celery) { + this.celery = celery; + } + + public boolean isSesameSeeds() { + return sesameSeeds; + } + + public void setSesameSeeds(boolean sesameSeeds) { + this.sesameSeeds = sesameSeeds; + } + + @Override + public String toString() { + return "AllergensAsEmbeddable [peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java new file mode 100644 index 0000000000..87a83157d7 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/multipletables/secondarytable/embeddable/MealWithEmbeddedAllergens.java @@ -0,0 +1,78 @@ +package com.baeldung.jpa.multipletables.secondarytable.embeddable; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.Table; + +@Entity +@Table(name = "meal") +@SecondaryTable(name = "allergens", pkJoinColumns = @PrimaryKeyJoinColumn(name = "meal_id")) +public class MealWithEmbeddedAllergens { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "price") + private BigDecimal price; + + @Embedded + private AllergensAsEmbeddable allergens; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public AllergensAsEmbeddable getAllergens() { + return allergens; + } + + public void setAllergens(AllergensAsEmbeddable allergens) { + this.allergens = allergens; + } + + public Long getId() { + return id; + } + + @Override + public String toString() { + return "MealWithEmbeddedAllergens [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", allergens=" + allergens + "]"; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/Exam.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/Exam.java new file mode 100644 index 0000000000..8bea8e0121 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/Exam.java @@ -0,0 +1,103 @@ +package com.baeldung.jpa.text; + +import javax.persistence.*; + +@Entity +public class Exam { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + @Lob + private String description; + @Column(columnDefinition = "text") + private String text; + @Column(length = 20) + private String shortText; + + public Exam() { + + } + + public Exam(String description, String text, String shortText) { + this.description = description; + this.text = text; + this.shortText = shortText; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getShortText() { + return shortText; + } + + public void setShortText(String shortText) { + this.shortText = shortText; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((shortText == null) ? 0 : shortText.hashCode()); + result = prime * result + ((text == null) ? 0 : text.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Exam other = (Exam) obj; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (shortText == null) { + if (other.shortText != null) + return false; + } else if (!shortText.equals(other.shortText)) + return false; + if (text == null) { + if (other.text != null) + return false; + } else if (!text.equals(other.text)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/ExamRepository.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/ExamRepository.java new file mode 100644 index 0000000000..2ee502bf4c --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/text/ExamRepository.java @@ -0,0 +1,39 @@ +package com.baeldung.jpa.text; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +public class ExamRepository { + + private EntityManagerFactory emf = null; + + public ExamRepository() { + emf = Persistence.createEntityManagerFactory("jpa-h2-text"); + } + + public Exam find(Long id) { + EntityManager entityManager = emf.createEntityManager(); + Exam exam = entityManager.find(Exam.class, id); + entityManager.close(); + return exam; + } + + public Exam save(Exam exam) { + + EntityManager entityManager = emf.createEntityManager(); + entityManager.getTransaction() + .begin(); + exam = entityManager.merge(exam); + entityManager.getTransaction() + .commit(); + entityManager.close(); + + return exam; + } + + public void clean() { + emf.close(); + } + +} diff --git a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml index 62d7ce0f5e..11e007973f 100644 --- a/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml @@ -1,41 +1,150 @@ + version="2.2"> - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.queryparams.Employee - true - - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.queryparams.Employee + true + + + + + + + + + + + + - + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.text.Exam + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.defaultvalues.User + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.querytypes.UserEntity + true + + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.projections.Product + true + + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.criteria.Item + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.defaultvalues.User + com.baeldung.jpa.multipletables.multipleentities.MealWithMultipleEntities + com.baeldung.jpa.multipletables.multipleentities.AllergensAsEntity + + com.baeldung.jpa.multipletables.secondarytable.MealAsSingleEntity + + com.baeldung.jpa.multipletables.secondarytable.embeddable.MealWithEmbeddedAllergens + com.baeldung.jpa.multipletables.secondarytable.embeddable.AllergensAsEmbeddable + true - + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.querytypes.UserEntity - true - - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.projections.Product - true - - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.criteria.Item - true - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java new file mode 100644 index 0000000000..99b2cd69ee --- /dev/null +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/multipletables/MultipleTablesIntegrationTest.java @@ -0,0 +1,79 @@ +package com.baeldung.jpa.multipletables; + +import static org.assertj.core.api.Assertions.*; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.jpa.multipletables.multipleentities.MealWithMultipleEntities; +import com.baeldung.jpa.multipletables.secondarytable.MealAsSingleEntity; +import com.baeldung.jpa.multipletables.secondarytable.embeddable.MealWithEmbeddedAllergens; + +public class MultipleTablesIntegrationTest { + + private static EntityManagerFactory emf; + private static EntityManager em; + + @BeforeClass + public static void setup() { + emf = Persistence.createEntityManagerFactory("jpa-h2-multipltables"); + em = emf.createEntityManager(); + } + + @Test + public void entityManager_shouldLoadMealAsSingleEntity() { + // given + + // when + MealAsSingleEntity meal = em.find(MealAsSingleEntity.class, 1L); + + // then + assertThat(meal).isNotNull(); + assertThat(meal.getId()).isEqualTo(1L); + assertThat(meal.isPeanuts()).isFalse(); + assertThat(meal.isCelery()).isTrue(); + } + + @Test + public void entityManager_shouldLoadMealWithEmbeddedAllergens() { + // given + + // when + MealWithEmbeddedAllergens meal = em.find(MealWithEmbeddedAllergens.class, 1L); + + // then + assertThat(meal).isNotNull(); + assertThat(meal.getId()).isEqualTo(1L); + assertThat(meal.getAllergens()).isNotNull(); + assertThat(meal.getAllergens().isPeanuts()).isFalse(); + assertThat(meal.getAllergens().isCelery()).isTrue(); + } + + @Test + public void entityManager_shouldLoadMealWithAllergensEntity() { + // given + + // when + MealWithMultipleEntities meal = em.find(MealWithMultipleEntities.class, 1L); + + // then + assertThat(meal).isNotNull(); + assertThat(meal.getId()).isEqualTo(1L); + assertThat(meal.getAllergens()).isNotNull(); + assertThat(meal.getAllergens().isPeanuts()).isFalse(); + assertThat(meal.getAllergens().isCelery()).isTrue(); + } + + @AfterClass + public static void teardown() { + if (emf != null) { + emf.close(); + } + } + +} diff --git a/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/text/JPATextUnitTest.java b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/text/JPATextUnitTest.java new file mode 100644 index 0000000000..f9f355c464 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/test/java/com/baeldung/jpa/text/JPATextUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.jpa.text; + +import static org.junit.Assert.assertEquals; + +import javax.persistence.PersistenceException; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class JPATextUnitTest { + + private static ExamRepository examRepository = null; + + @BeforeClass + public static void once() { + examRepository = new ExamRepository(); + } + + @Test + public void givenExam_whenSaveExam_thenReturnExpectedExam() { + Exam exam = new Exam(); + exam.setDescription("This is a description. Sometimes the description can be very very long! "); + exam.setText("This is a text. Sometimes the text can be very very long!"); + exam.setShortText("A short text"); + + exam = examRepository.save(exam); + + assertEquals(examRepository.find(exam.getId()), exam); + } + + @Test(expected = PersistenceException.class) + public void givenExamWithVeryLongShortText_whenSaveExam_thenThrowPersistenceException() { + Exam exam = new Exam(); + exam.setDescription("This is a very long text"); + exam.setText("This is a long text"); + exam.setShortText("This is a very long long short text. Maybe this can cause problems!!"); + + examRepository.save(exam); + } + +} \ No newline at end of file diff --git a/persistence-modules/java-jpa-2/src/test/resources/multipletables.sql b/persistence-modules/java-jpa-2/src/test/resources/multipletables.sql new file mode 100644 index 0000000000..226e63258b --- /dev/null +++ b/persistence-modules/java-jpa-2/src/test/resources/multipletables.sql @@ -0,0 +1,8 @@ +drop table if exists allergens; +drop table if exists meal; + +create table meal (id bigint auto_increment, name varchar(255) not null, description varchar(255) not null, price decimal(19, 2) not null, primary key (id)); +create table allergens (meal_id bigint auto_increment, peanuts number(1) not null, celery number(1) not null, sesame_seeds number(1) not null, primary key (meal_id)); + +insert into meal (id, name, description, price) values (1, 'Pizza', 'Delicious', 5); +insert into allergens (meal_id, peanuts, celery, sesame_seeds) values (1, 0, 1, 0); diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index f1542e3ee9..41d0ad63f8 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -1,4 +1,8 @@ -## Relevant articles: +## MongoDB + +This module contains articles about MongoDB in Java. + +### Relevant articles: - [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb) - [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging) diff --git a/persistence-modules/jnosql/README.md b/persistence-modules/jnosql/README.md index d580cbc920..cb126914e9 100644 --- a/persistence-modules/jnosql/README.md +++ b/persistence-modules/jnosql/README.md @@ -1,2 +1,6 @@ +## JNoSQL + +This module contains articles about JNoSQL. + ### Relevant Articles: - [A Guide to Eclipse JNoSQL](http://www.baeldung.com/eclipse-jnosql) 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/pom.xml b/persistence-modules/pom.xml index 932b62a235..de20b135fa 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -23,7 +23,7 @@ hibernate5 hibernate-ogm hibernate-mapping - hibernate-parameters + hibernate5-2 influxdb java-cassandra java-cockroachdb @@ -48,7 +48,9 @@ spring-data-eclipselink spring-data-elasticsearch spring-data-gemfire + spring-data-geode spring-data-jpa + spring-data-jpa-3 spring-data-keyvalue spring-data-mongodb spring-data-neo4j @@ -60,7 +62,7 @@ spring-jpa spring-persistence-simple jpa-hibernate-cascade-type - r2dbc + r2dbc spring-boot-jdbi diff --git a/persistence-modules/sirix/README.md b/persistence-modules/sirix/README.md index b0f6f8d04b..ab7fb65e44 100644 --- a/persistence-modules/sirix/README.md +++ b/persistence-modules/sirix/README.md @@ -1,3 +1,4 @@ ## Relevant articles: -- [Introduction to Sirix](https://www.baeldung.com/introduction-to-sirix) \ No newline at end of file +- [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-geode/pom.xml b/persistence-modules/spring-data-geode/pom.xml new file mode 100644 index 0000000000..abd3049755 --- /dev/null +++ b/persistence-modules/spring-data-geode/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + spring-data-geode + spring-data-geode + jar + Intro to Spring Data Geode + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + org.springframework.boot + spring-boot-starter + 2.1.9.RELEASE + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-web + ${spring-boot-version} + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.geode + spring-geode-starter + ${spring-geode-starter-version} + + + + org.springframework.boot + spring-boot-autoconfigure + ${spring-boot-version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-version} + test + + + + + ${project.artifactId} + + + com.mysema.maven + maven-apt-plugin + 1.0 + + + generate-sources + + process + + + target/generated-sources + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-version} + + + + + + 2.1.9.RELEASE + UTF-8 + com.baeldung.springdatageode.app.ClientCacheApp + 1.1.1.RELEASE + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/app/ClientCacheApp.java b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/app/ClientCacheApp.java new file mode 100644 index 0000000000..6e9a33e953 --- /dev/null +++ b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/app/ClientCacheApp.java @@ -0,0 +1,32 @@ +package com.baeldung.springdatageode.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.gemfire.config.annotation.ClientCacheApplication; +import org.springframework.data.gemfire.config.annotation.EnableClusterConfiguration; +import org.springframework.data.gemfire.config.annotation.EnableContinuousQueries; +import org.springframework.data.gemfire.config.annotation.EnableEntityDefinedRegions; +import org.springframework.data.gemfire.config.annotation.EnableIndexing; +import org.springframework.data.gemfire.repository.config.EnableGemfireRepositories; + +import com.baeldung.springdatageode.controller.AppController; +import com.baeldung.springdatageode.domain.Author; +import com.baeldung.springdatageode.repo.AuthorRepository; +import com.baeldung.springdatageode.service.AuthorService; + +@SpringBootApplication +@ClientCacheApplication(subscriptionEnabled = true) +@EnableEntityDefinedRegions(basePackageClasses = Author.class) +@EnableIndexing +@EnableGemfireRepositories(basePackageClasses = AuthorRepository.class) +@ComponentScan(basePackageClasses = {AppController.class, AuthorService.class}) +@EnableClusterConfiguration(useHttp = true, requireHttps=false) +@EnableContinuousQueries +public class ClientCacheApp { + + public static void main(String[] args) { + SpringApplication.run(ClientCacheApp.class, args); + } + +} diff --git a/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/controller/AppController.java b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/controller/AppController.java new file mode 100644 index 0000000000..32f931820a --- /dev/null +++ b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/controller/AppController.java @@ -0,0 +1,37 @@ +package com.baeldung.springdatageode.controller; + +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.springdatageode.domain.Author; +import com.baeldung.springdatageode.repo.AuthorRepository; + +@RestController +@CrossOrigin +public class AppController { + + @Autowired + private AuthorRepository authorRepositoryImpl; + + @PostMapping(path = "/author" ) + public ResponseEntity addAuthor(@RequestBody Author author) throws Exception { + authorRepositoryImpl.save(author); + return new ResponseEntity<>("OK", HttpStatus.OK); + } + + @GetMapping(path = "/author" ) + public ResponseEntity getAuthor(@RequestParam("id") String id) throws Exception { + Optional author = authorRepositoryImpl.findById(Long.parseLong(id)); + return new ResponseEntity<>(author.isPresent() ? author.get() : null, HttpStatus.OK); + } + +} diff --git a/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/domain/Author.java b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/domain/Author.java new file mode 100644 index 0000000000..4a2e58ff34 --- /dev/null +++ b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/domain/Author.java @@ -0,0 +1,58 @@ +package com.baeldung.springdatageode.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.gemfire.mapping.annotation.Indexed; +import org.springframework.data.gemfire.mapping.annotation.Region; + +@Region(name = "Authors") +public class Author { + + @Id + private Long id; + + private String firstName; + + private String lastName; + + @Indexed + private int age; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return this.firstName + " " + this.lastName + ", " + this.age + " years old"; + } + +} + diff --git a/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/repo/AuthorRepository.java b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/repo/AuthorRepository.java new file mode 100644 index 0000000000..92f4165343 --- /dev/null +++ b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/repo/AuthorRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.springdatageode.repo; + +import com.baeldung.springdatageode.domain.Author; + +import java.util.Optional; + +import org.springframework.data.repository.CrudRepository; + +public interface AuthorRepository extends CrudRepository { + +} diff --git a/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/service/AuthorService.java b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/service/AuthorService.java new file mode 100644 index 0000000000..1bf4cbaba1 --- /dev/null +++ b/persistence-modules/spring-data-geode/src/main/java/com/baeldung/springdatageode/service/AuthorService.java @@ -0,0 +1,14 @@ +package com.baeldung.springdatageode.service; + +import org.apache.geode.cache.query.CqEvent; +import org.springframework.data.gemfire.listener.annotation.ContinuousQuery; +import org.springframework.stereotype.Service; + +@Service +public class AuthorService { + + @ContinuousQuery(query = "SELECT * FROM /Authors a WHERE a.id = 1") + public void process(CqEvent event) { + System.out.println("Author #" + event.getKey() + " updated to " + event.getNewValue()); + } +} diff --git a/persistence-modules/spring-data-geode/src/main/resources/application.properties b/persistence-modules/spring-data-geode/src/main/resources/application.properties new file mode 100644 index 0000000000..7b7cb5a37b --- /dev/null +++ b/persistence-modules/spring-data-geode/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=9091 \ No newline at end of file diff --git a/persistence-modules/spring-data-geode/src/main/resources/logback.xml b/persistence-modules/spring-data-geode/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/spring-data-geode/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/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 new file mode 100644 index 0000000000..f743fce2a3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/pom.xml @@ -0,0 +1,78 @@ + + + + 4.0.0 + spring-data-jpa-3 + spring-data-jpa-3 + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + ${postgresql.version} + + + + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-launcher + ${junit-platform.version} + test + + + + + 1.12.2 + 42.2.8 + + + diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..c0490d50c6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/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/tx/Payment.java new file mode 100644 index 0000000000..37f3d09381 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/tx/Payment.java @@ -0,0 +1,55 @@ +package com.baeldung.tx; + +import javax.persistence.*; + +@Entity +public class Payment { + + @Id + @GeneratedValue + private Long id; + + private Long amount; + + @Column(unique = true) + private String referenceNumber; + + @Enumerated(EnumType.STRING) + private State state; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + + public String getReferenceNumber() { + return referenceNumber; + } + + public void setReferenceNumber(String referenceNumber) { + this.referenceNumber = referenceNumber; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public enum State { + STARTED, FAILED, SUCCESSFUL + } +} 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 new file mode 100644 index 0000000000..62d64d4372 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java @@ -0,0 +1,171 @@ +package com.baeldung.tx; + +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; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +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; + + @Autowired + private EntityManager entityManager; + + private TransactionTemplate transactionTemplate; + + @BeforeEach + void setUp() { + transactionTemplate = new TransactionTemplate(transactionManager); + } + + @AfterEach + void flushDb() { + transactionTemplate.execute(status -> entityManager + .createQuery("delete from Payment") + .executeUpdate()); + } + + @Test + void givenAPayment_WhenNotDuplicate_ThenShouldCommit() { + Long id = transactionTemplate.execute(status -> { + Payment payment = new Payment(); + payment.setAmount(1000L); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + + return payment.getId(); + }); + + Payment payment = entityManager.find(Payment.class, id); + assertThat(payment).isNotNull(); + } + + @Test + void givenAPayment_WhenMarkAsRollback_ThenShouldRollback() { + transactionTemplate.execute(status -> { + Payment payment = new Payment(); + payment.setAmount(1000L); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + status.setRollbackOnly(); + + return payment.getId(); + }); + + assertThat(entityManager + .createQuery("select p from Payment p") + .getResultList()).isEmpty(); + } + + @Test + void givenTwoPayments_WhenRefIsDuplicate_ThenShouldRollback() { + try { + transactionTemplate.execute(s -> { + Payment first = new Payment(); + first.setAmount(1000L); + first.setReferenceNumber("Ref-1"); + first.setState(Payment.State.SUCCESSFUL); + + Payment second = new Payment(); + second.setAmount(2000L); + second.setReferenceNumber("Ref-1"); + second.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(first); + entityManager.persist(second); + + return "Ref-1"; + }); + } catch (Exception ignored) { + } + + assertThat(entityManager + .createQuery("select p from Payment p") + .getResultList()).isEmpty(); + } + + @Test + void givenAPayment_WhenNotExpectingAnyResult_ThenShouldCommit() { + transactionTemplate.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + Payment payment = new Payment(); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + } + }); + + assertThat(entityManager + .createQuery("select p from Payment p") + .getResultList()).hasSize(1); + } + + @Test + void givenAPayment_WhenUsingTxManager_ThenShouldCommit() { + DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); + definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + definition.setTimeout(3); + + TransactionStatus status = transactionManager.getTransaction(definition); + try { + Payment payment = new Payment(); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + transactionManager.commit(status); + } catch (Exception ex) { + transactionManager.rollback(status); + } + + assertThat(entityManager + .createQuery("select p from Payment p") + .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 new file mode 100644 index 0000000000..aa7093f751 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties @@ -0,0 +1,4 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:postgresql://localhost:54320/baeldung +spring.datasource.username=test +spring.datasource.password=test 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/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java new file mode 100644 index 0000000000..6f2a499bc5 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java @@ -0,0 +1,250 @@ +package com.baeldung.persistence.service.transactional; + +import com.baeldung.persistence.model.Foo; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceTransactionalTestConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext +public class FooTransactionalUnitTest { + + static abstract class BasicFooDao { + @PersistenceContext private EntityManager entityManager; + + public Foo findOne(final long id) { + return entityManager.find(Foo.class, id); + } + + public Foo create(final Foo entity) { + entityManager.persist(entity); + return entity; + } + } + + @Repository + static class RequiredTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.REQUIRED) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class RequiresNewTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class SupportTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.SUPPORTS) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class MandatoryTransactionalFooDao extends BasicFooDao { + @Override + @Transactional(propagation = Propagation.MANDATORY) + public Foo create(Foo entity) { + return super.create(entity); + } + } + + @Repository + static class SupportTransactionalFooService { + @Transactional(propagation = Propagation.SUPPORTS) + public Foo identity(Foo entity) { + return entity; + } + } + + @Service + static class MandatoryTransactionalFooService { + @Transactional(propagation = Propagation.MANDATORY) + public Foo identity(Foo entity) { + return entity; + } + } + + @Service + static class NotSupportedTransactionalFooService { + @Transactional(propagation = Propagation.NOT_SUPPORTED) + public Foo identity(Foo entity) { + return entity; + } + } + + @Service + static class NeverTransactionalFooService { + @Transactional(propagation = Propagation.NEVER) + public Foo identity(Foo entity) { + return entity; + } + } + + @Autowired private TransactionTemplate transactionTemplate; + + @Autowired private RequiredTransactionalFooDao requiredTransactionalFooDao; + + @Autowired private RequiresNewTransactionalFooDao requiresNewTransactionalFooDao; + + @Autowired private SupportTransactionalFooDao supportTransactionalFooDao; + + @Autowired private MandatoryTransactionalFooDao mandatoryTransactionalFooDao; + + @Autowired private MandatoryTransactionalFooService mandatoryTransactionalFooService; + + @Autowired private NeverTransactionalFooService neverTransactionalFooService; + + @Autowired private NotSupportedTransactionalFooService notSupportedTransactionalFooService; + + @Autowired private SupportTransactionalFooService supportTransactionalFooService; + + @After + public void tearDown(){ + PersistenceTransactionalTestConfig.clearSpy(); + } + + @Test + public void givenRequiredWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { + requiredTransactionalFooDao.create(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + + + @Test + public void givenRequiresNewWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { + requiresNewTransactionalFooDao.create(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { + supportTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test(expected = IllegalTransactionStateException.class) + public void givenMandatoryWithNoActiveTransaction_whenCallService_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { + mandatoryTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test + public void givenNotSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { + notSupportedTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test + public void givenNeverWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { + neverTransactionalFooService.identity(new Foo("baeldung")); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(0, transactionSpy.getCreate()); + } + + @Test + public void givenRequiredWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return requiredTransactionalFooDao.create(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenRequiresNewWithActiveTransaction_whenCallCreate_thenExpect1NewAnd1Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return requiresNewTransactionalFooDao.create(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(1, transactionSpy.getSuspend()); + Assert.assertEquals(2, transactionSpy.getCreate()); + } + + @Test + public void givenSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return supportTransactionalFooDao.create(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenMandatoryWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { + + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return mandatoryTransactionalFooDao.create(foo); + }); + + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test + public void givenNotSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd1Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return notSupportedTransactionalFooService.identity(foo); + }); + + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(1, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + + @Test(expected = IllegalTransactionStateException.class) + public void givenNeverWithActiveTransaction_whenCallCreate_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { + transactionTemplate.execute(status -> { + Foo foo = new Foo("baeldung"); + return neverTransactionalFooService.identity(foo); + }); + PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); + Assert.assertEquals(0, transactionSpy.getSuspend()); + Assert.assertEquals(1, transactionSpy.getCreate()); + } + +} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java new file mode 100644 index 0000000000..fde1857ca2 --- /dev/null +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java @@ -0,0 +1,148 @@ +package com.baeldung.persistence.service.transactional; + +import com.google.common.base.Preconditions; +import java.util.Properties; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationAdapter; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-h2.properties" }) +@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" }) +@EnableJpaRepositories(basePackages = "com.baeldung.jpa.dao") +public class PersistenceTransactionalTestConfig { + + public static class TransactionSynchronizationAdapterSpy extends TransactionSynchronizationAdapter { + private int create, suspend; + + public int getSuspend() { + return suspend; + } + + public int getCreate() { + return create; + } + + public void create() { + create++; + } + + @Override + public void suspend() { + suspend++; + super.suspend(); + } + } + + + public static class JpaTransactionManagerSpy extends JpaTransactionManager { + @Override + protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) { + super.prepareSynchronization(status, definition); + if (status.isNewTransaction()) { + if ( adapterSpyThreadLocal.get() == null ){ + TransactionSynchronizationAdapterSpy spy = new TransactionSynchronizationAdapterSpy(); + TransactionSynchronizationManager.registerSynchronization(spy); + adapterSpyThreadLocal.set(spy); + } + adapterSpyThreadLocal.get().create(); + } + } + } + + private static ThreadLocal adapterSpyThreadLocal = new ThreadLocal<>(); + + @Autowired + private Environment env; + + public PersistenceTransactionalTestConfig() { + super(); + } + + public static TransactionSynchronizationAdapterSpy getSpy(){ + if ( adapterSpyThreadLocal.get() == null ) + return new TransactionSynchronizationAdapterSpy(); + return adapterSpyThreadLocal.get(); + } + + public static void clearSpy(){ + adapterSpyThreadLocal.set(null); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManagerSpy transactionManager = new JpaTransactionManagerSpy(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); + return hibernateProperties; + } + + + @Bean + public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager){ + TransactionTemplate template = new TransactionTemplate(transactionManager); + template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + return template; + } + + +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 12f33c5187..f5776731c9 100644 --- a/pom.xml +++ b/pom.xml @@ -1,415 +1,425 @@ - 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"> + 4.0.0 - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - parent-modules - pom + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + parent-modules + pom - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - ch.qos.logback - logback-core - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + - - - junit - junit - ${junit.version} - test - - - org.junit.jupiter - junit-jupiter-engine - ${junit-jupiter.version} - test - - - org.junit.jupiter - junit-jupiter-params - ${junit-jupiter.version} - test - - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter.version} - test - - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-all - ${org.hamcrest.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.apache.maven.surefire - surefire-logger-api - ${maven-surefire-plugin.version} - - test - true - - + + + junit + junit + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-all + ${org.hamcrest.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.apache.maven.surefire + surefire-logger-api + ${maven-surefire-plugin.version} + + test + true + + - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - maven - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - - - org.junit.platform - junit-platform-surefire-provider - ${junit-platform.version} - - - org.junit.jupiter - junit-jupiter-engine - ${junit-jupiter.version} - - - org.junit.vintage - junit-vintage-engine - ${junit-jupiter.version} - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - org.apache.maven.plugins - maven-pmd-plugin - ${maven-pmd-plugin.version} - - - org.baeldung.pmd - custom-pmd - ${custom-pmd.version} - - - - 5 - false - true - true - true - true - UTF-8 - ${java.version} - - ${tutorialsproject.basedir}/baeldung-pmd-rules.xml - - - target/generated-sources - - - - - compile - - check - - - - - - org.commonjava.maven.plugins - directory-maven-plugin - ${directory-maven-plugin.version} - - - directories - - directory-of - - validate - - tutorialsproject.basedir - - com.baeldung - parent-modules - - - - - - - org.apache.maven.plugins - maven-install-plugin - ${maven-install-plugin.version} - - org.baeldung.pmd - custom-pmd - ${custom-pmd.version} - jar - ${tutorialsproject.basedir}/custom-pmd-${custom-pmd.version}.jar - true - - - - install-jar-lib - - install-file - - validate - - - - - maven-war-plugin - ${maven-war-plugin.version} - - + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + maven + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + org.junit.platform + junit-platform-surefire-provider + ${junit-platform.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven-pmd-plugin.version} + + + org.baeldung.pmd + custom-pmd + ${custom-pmd.version} + + + + 5 + false + true + true + true + true + UTF-8 + ${java.version} + + ${tutorialsproject.basedir}/baeldung-pmd-rules.xml + + + target/generated-sources + + + + + compile + + check + + + + + + org.commonjava.maven.plugins + directory-maven-plugin + ${directory-maven-plugin.version} + + + directories + + directory-of + + validate + + tutorialsproject.basedir + + com.baeldung + parent-modules + + + + + + + org.apache.maven.plugins + maven-install-plugin + ${maven-install-plugin.version} + + org.baeldung.pmd + custom-pmd + ${custom-pmd.version} + jar + ${tutorialsproject.basedir}/custom-pmd-${custom-pmd.version}.jar + true + + + + install-jar-lib + + install-file + + validate + + + + + maven-war-plugin + ${maven-war-plugin.version} + + - - - com.vackosar.gitflowincrementalbuilder - gitflow-incremental-builder - ${gitflow-incremental-builder.version} - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.commonjava.maven.plugins - - - directory-maven-plugin - - - [0.3.1,) - - - directory-of - - - - - - - - - - org.apache.maven.plugins - - - maven-install-plugin - - - [2.5.1,) - - - install-file - - - - - - - - - - - - - + + + com.vackosar.gitflowincrementalbuilder + gitflow-incremental-builder + ${gitflow-incremental-builder.version} + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.commonjava.maven.plugins + + + directory-maven-plugin + + + [0.3.1,) + + + directory-of + + + + + + + + + + org.apache.maven.plugins + + + maven-install-plugin + + + [2.5.1,) + + + install-file + + + + + + + + + + + + + - + - - default-first - - + + default-first + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - SpringContextTest - **/*UnitTest - - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/JdbcTest.java - **/*LiveTest.java - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + SpringContextTest + **/*UnitTest + + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + - - + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-miscellaneous-4 - algorithms-miscellaneous-5 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-olingo/olingo2 - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - aws - aws-lambda - axon - azure + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-miscellaneous-4 + algorithms-miscellaneous-5 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-olingo/olingo2 + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + aws + aws-lambda + axon + azure - bazel - blade - bootique + bazel + blade + bootique - cas - cdi - checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server - code-generation - core-groovy - core-groovy-2 - core-groovy-collections - - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - core-java-modules/core-java-datetime - core-java-modules/core-java-text - core-java-modules/core-java-lambdas + cas + cdi + checker-plugin + cloud-foundry-uaa/cf-uaa-oauth2-client + cloud-foundry-uaa/cf-uaa-oauth2-resource-server + code-generation + core-groovy + core-groovy-2 + core-groovy-collections + + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 + core-java-modules/core-java-annotations + core-java-modules/core-java-streams + core-java-modules/core-java-streams-2 + core-java-modules/core-java-streams-3 + + core-java-modules/core-java-function + core-java-modules/core-java-lang-math + + + core-java-modules/core-java-text + core-java-modules/core-java-lambdas core-java-modules/core-java-arrays core-java-modules/core-java-arrays-2 core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 + core-java-modules/core-java-collections-2 + core-java-modules/core-java-collections-3 core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 core-java-modules/core-java-collections-list-3 core-java-modules/core-java-collections-array-list core-java-modules/core-java-collections-set core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 + core-java-modules/core-java-concurrency-basic-2 core-java-modules/core-java-concurrency-collections core-java-modules/core-java-io core-java-modules/core-java-io-files @@ -419,10 +429,10 @@ core-java-modules/core-java-lang-syntax core-java-modules/core-java-lang-syntax-2 core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 + core-java-modules/core-java-lang-2 core-java-modules/core-java-lang-oop core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 + core-java-modules/core-java-lang-oop-3 core-java-modules core-java-modules/core-java-networking core-java-modules/core-java-perf @@ -430,6 +440,11 @@ 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 core-java-modules/core-java-jvm core-scala @@ -459,7 +474,7 @@ grpc gson guava - guava-io + guava-io guava-collections guava-collections-map guava-collections-set @@ -480,23 +495,20 @@ jackson-2 jackson-simple java-collections-conversions + java-collections-conversions-2 java-collections-maps java-collections-maps-2 java-jdi - - + java-lite - java-math + java-math java-numbers 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 @@ -506,1205 +518,1214 @@ jaxb - jee-7-security - jee-kotlin - jersey - jgit - jgroups - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jee-kotlin + jersey + jgit + jgroups + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries - kotlin-libraries-2 + + kotlin-libraries + kotlin-libraries-2 - - libraries - libraries-2 - libraries-data - libraries-data-2 - libraries-data-db + + libraries + libraries-2 + libraries-data + libraries-data-2 + libraries-data-db libraries-data-io libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-primitive - libraries-testing - libraries-security - libraries-server - libraries-http - libraries-io - linkrest - logging-modules - lombok - lucene + libraries-apache-commons-collections + libraries-apache-commons-io + libraries-primitive + libraries-testing + libraries-security + libraries-server + libraries-http + libraries-io + linkrest + logging-modules + lombok + lucene - mapstruct - - maven-all/maven - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + + maven-all/maven + maven-all/maven-war-plugin + maven-all/profiles + maven-all/versions-maven-plugin + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules - quarkus + persistence-modules + quarkus - rabbitmq - - ratpack - reactor-core - resteasy - restx - - rule-engines - rsocket - rxjava - rxjava-2 - software-security/sql-injection-samples + rabbitmq + + ratpack + reactor-core + resteasy + restx + + rule-engines + rsocket + rxjava + rxjava-2 + software-security/sql-injection-samples - tensorflow-java - spf4j - spring-boot-configuration + tensorflow-java + spf4j + spring-boot-configuration spring-boot-flowable - spring-boot-mvc-2 - spring-boot-performance - spring-boot-properties - + spring-boot-mvc-2 + spring-boot-performance + spring-boot-properties + + spring-security-kerberos + oauth2-framework-impl - spring-security-kerberos - oauth2-framework-impl - - spring-boot-nashorn - java-blockchain - wildfly - - + spring-boot-nashorn + java-blockchain + wildfly + - + - - default-second - - + + default-second + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - SpringContextTest - **/*UnitTest - - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*JdbcTest.java - **/*LiveTest.java - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + SpringContextTest + **/*UnitTest + + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + - - + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-webflux - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-2 - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito + spring-5 + spring-5-webflux + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-2 + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito - spring-activiti - spring-akka - spring-amqp - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-activiti + spring-akka + spring-amqp + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-configuration + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-configuration spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-kotlin - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-environment + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-kotlin + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-environment spring-boot-deployment spring-boot-runtime spring-boot-runtime/disabling-console-jul spring-boot-runtime/disabling-console-log4j2 - spring-boot-runtime/disabling-console-logback - spring-boot-artifacts - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-testing - spring-boot-vue - spring-caching + spring-boot-runtime/disabling-console-logback + spring-boot-artifacts + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-testing + spring-boot-vue + spring-caching spring-boot-libraries - - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow - spring-core - spring-core-2 - spring-core-3 + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow + + spring-core + spring-core-2 + spring-core-3 spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools - spring-di + spring-data-rest + spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools + spring-di - spring-ehcache - spring-ejb - spring-exceptions + spring-ehcache + spring-ejb + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-basics-2 + spring-mobile + spring-mockito + spring-mvc-basics-2 spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-compress - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-compress + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo + spring-schedulingspring-security-acl + spring-security-angular/server + spring-security-cache-control - spring-scheduling - spring-security-acl - spring-security-angular/server - spring-security-cache-control - - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-jsonview - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc - spring-security-mvc-socket - spring-security-openid - - spring-security-rest - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session - spring-shell + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-jsonview + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc + spring-security-mvc-socket + spring-security-openid + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-shell spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-vault - spring-vertx + spring-vault + spring-vertx - spring-webflux-amqp + spring-webflux-amqp - spring-zuul + spring-zuul - static-analysis - stripe - structurizr - struts-2 + static-analysis + stripe + structurizr + struts-2 - testing-modules + testing-modules - twilio - twitter4j + twilio + twitter4j - undertow + undertow - vertx - vertx-and-rxjava - video-tutorials - vraptor + vertx + vertx-and-rxjava + video-tutorials + vraptor - wicket + wicket - xml - xstream + xml + xstream - tensorflow-java - spring-boot-flowable - spring-security-kerberos - - spring-boot-nashorn - java-blockchain + tensorflow-java + spring-boot-flowable + spring-security-kerberos - + spring-boot-nashorn + java-blockchain - + - - spring-context - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*SpringContextIntegrationTest.java - - - + + spring-context + + - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*SpringContextIntegrationTest.java + + + - - spring-5 - spring-5-data-reactive - spring-5-reactive - spring-5-reactive-2 - spring-5-reactive-client - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito - spring-activiti - spring-akka - spring-aop - spring-apache-camel - spring-batch - spring-bom - spring-boot-admin - spring-boot-bootstrap - spring-boot-bootstrap - spring-boot-camel - spring-boot-client - spring-boot-custom-starter - spring-boot-di - greeter-spring-boot-autoconfigure - greeter-spring-boot-sample-app - persistence-modules/spring-boot-h2/spring-boot-h2-database - spring-boot-jasypt - spring-boot-keycloak - spring-boot-mvc - spring-boot-property-exp - spring-boot-vue - spring-cloud - spring-cloud/spring-cloud-archaius/basic-config - spring-cloud/spring-cloud-archaius/extra-configs - spring-cloud/spring-cloud-bootstrap/config - spring-cloud/spring-cloud-contract - spring-cloud/spring-cloud-gateway - spring-cloud/spring-cloud-kubernetes/demo-backend - spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server - spring-cloud/spring-cloud-ribbon-client - spring-cloud/spring-cloud-security - spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit - spring-cloud/spring-cloud-task/springcloudtasksink - spring-cloud/spring-cloud-zookeeper - spring-cloud/spring-cloud-bus/spring-cloud-config-server - spring-cloud/spring-cloud-data-flow/log-sink - spring-cloud/spring-cloud-data-flow/time-processor - spring-cloud/spring-cloud-data-flow/time-source - spring-cucumber - persistence-modules/spring-data-keyvalue - spring-data-rest - spring-dispatcher-servlet - spring-drools - spring-di - spring-ehcache - spring-freemarker - persistence-modules/spring-hibernate-3 - persistence-modules/spring-hibernate4 - persistence-modules/spring-mybatis - spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-kafka - spring-katharsis - spring-ldap - spring-mobile - spring-mockito - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-velocity - spring-mvc-webflow - spring-protobuf - spring-quartz - remoting-hessian-burlap/spring-remoting-hessian-burlap-client - remoting-hessian-burlap/remoting-hessian-burlap-server - spring-reactor - spring-remoting/ - spring-remoting/remoting-http/remoting-http-server - spring-remoting/remoting-jms/remoting-jms-client - spring-remoting/remoting-rmi/remoting-rmi-server - spring-rest - spring-rest-angular - spring-rest-compress - spring-rest-full - spring-rest-simple - spring-resttemplate - spring-security-acl - spring-security-angular - spring-security-cache-control - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-persisted-remember-me - spring-security-mvc - spring-security-mvc-socket - spring-security-rest - spring-security-sso - spring-security-thymeleaf/spring-security-thymeleaf-authentication - spring-security-thymeleaf/spring-security-thymeleaf-authorize - spring-security-thymeleaf/spring-security-thymeleaf-config - spring-security-x509 - spring-session/spring-session-jdbc - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-swagger-codegen/spring-swagger-codegen-app - spring-thymeleaf - spring-vault - spring-vertx - spring-zuul/spring-zuul-foos-resource - persistence-modules/hibernate-mapping - persistence-modules/spring-data-dynamodb - persistence-modules/spring-data-eclipselink - persistence-modules/spring-data-solr - persistence-modules/spring-hibernate-5 + + - spring-boot-flowable - spring-security-kerberos - spring-boot-nashorn - + + spring-5 + spring-5-data-reactive + spring-5-reactive + spring-5-reactive-2 + spring-5-reactive-client + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito + spring-activiti + spring-akka + spring-aop + spring-apache-camel + spring-batch + spring-bom + spring-boot-admin + spring-boot-bootstrap + spring-boot-bootstrap + spring-boot-camel + spring-boot-client + spring-boot-custom-starter + spring-boot-di + greeter-spring-boot-autoconfigure + greeter-spring-boot-sample-app + persistence-modules/spring-boot-h2/spring-boot-h2-database + spring-boot-jasypt + spring-boot-keycloak + spring-boot-mvc + spring-boot-property-exp + spring-boot-vue + spring-cloud + spring-cloud/spring-cloud-archaius/basic-config + spring-cloud/spring-cloud-archaius/extra-configs + spring-cloud/spring-cloud-bootstrap/config + spring-cloud/spring-cloud-contract + spring-cloud/spring-cloud-gateway + spring-cloud/spring-cloud-kubernetes/demo-backend + spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server + spring-cloud/spring-cloud-ribbon-client + spring-cloud/spring-cloud-security + spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit + spring-cloud/spring-cloud-task/springcloudtasksink + spring-cloud/spring-cloud-zookeeper + spring-cloud/spring-cloud-bus/spring-cloud-config-server + spring-cloud/spring-cloud-data-flow/log-sink + spring-cloud/spring-cloud-data-flow/time-processor + spring-cloud/spring-cloud-data-flow/time-source + spring-cucumber + persistence-modules/spring-data-keyvalue + spring-data-rest + spring-dispatcher-servlet + spring-drools + spring-di + spring-ehcache + spring-freemarker + persistence-modules/spring-hibernate-3 + persistence-modules/spring-hibernate4 + persistence-modules/spring-mybatis + spring-integration + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-kafka + spring-katharsis + spring-ldap + spring-mobile + spring-mockito + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-velocity + spring-mvc-webflow + spring-protobuf + spring-quartz + remoting-hessian-burlap/spring-remoting-hessian-burlap-client + remoting-hessian-burlap/remoting-hessian-burlap-server + spring-reactor + spring-remoting/ + spring-remoting/remoting-http/remoting-http-server + spring-remoting/remoting-jms/remoting-jms-client + spring-remoting/remoting-rmi/remoting-rmi-server + spring-rest + spring-rest-angular + spring-rest-compress + spring-rest-full + spring-rest-simple + spring-resttemplate + spring-security-acl + spring-security-angular + spring-security-cache-control + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-persisted-remember-me + spring-security-mvc + spring-security-mvc-socket + spring-security-rest + spring-security-sso + spring-security-thymeleaf/spring-security-thymeleaf-authentication + spring-security-thymeleaf/spring-security-thymeleaf-authorize + spring-security-thymeleaf/spring-security-thymeleaf-config + spring-security-x509 + spring-session/spring-session-jdbc + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-swagger-codegen/spring-swagger-codegen-app + spring-thymeleaf + spring-vault + spring-vertx + spring-zuul/spring-zuul-foos-resource + persistence-modules/hibernate-mapping + persistence-modules/spring-data-dynamodb + persistence-modules/spring-data-eclipselink + persistence-modules/spring-data-solr + persistence-modules/spring-hibernate-5 - + spring-boot-flowable + spring-security-kerberos + spring-boot-nashorn + - - default-heavy - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - SpringContextTest - **/*UnitTest - - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*JdbcTest.java - **/*LiveTest.java - - - + + default-heavy + + - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + SpringContextTest + **/*UnitTest + + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + - core-java-modules/core-java-concurrency-advanced + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + core-java-modules/core-java-concurrency-advanced core-java-modules/core-java-concurrency-advanced-2 core-java-modules/core-java-concurrency-advanced-3 core-kotlin - core-kotlin-2 - core-kotlin-io + core-kotlin-2 + core-kotlin-io - jenkins/plugins - jhipster - jws + jenkins/plugins + jhipster + jws - libraries - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql + libraries + persistence-modules/hibernate5 + persistence-modules/hibernate-mapping + persistence-modules/java-jpa + persistence-modules/java-jpa-2 + persistence-modules/java-mongodb + persistence-modules/jnosql - vaadin - vavr - - + vaadin + vavr + + - - integration-lite-first + + integration-lite-first - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-miscellaneous-4 - algorithms-miscellaneous-5 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-olingo/olingo2 - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - aws - aws-lambda - axon - azure - bazel - bootique + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-miscellaneous-4 + algorithms-miscellaneous-5 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-olingo/olingo2 + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + aws + aws-lambda + axon + azure + bazel + bootique - cas - cdi - checker-plugin - cloud-foundry-uaa/cf-uaa-oauth2-client - cloud-foundry-uaa/cf-uaa-oauth2-resource-server - code-generation - core-groovy - core-groovy-2 - core-groovy-collections - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - core-java-modules/core-java-annotations - core-java-modules/core-java-streams - core-java-modules/core-java-function - core-java-modules/core-java-lang-math - core-java-modules/core-java-datetime - core-java-modules/core-java-text - - - core-java-modules/core-java-arrays - core-java-modules/core-java-arrays-2 - core-java-modules/core-java-collections - core-java-modules/core-java-collections-2 - core-java-modules/core-java-collections-3 - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-list-3 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-basic-2 - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-io-files - core-java-modules/core-java-nio - core-java-modules/core-java-security + cas + cdi + checker-plugin + cloud-foundry-uaa/cf-uaa-oauth2-client + cloud-foundry-uaa/cf-uaa-oauth2-resource-server + code-generation + core-groovy + core-groovy-2 + core-groovy-collections + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 + core-java-modules/core-java-annotations + core-java-modules/core-java-streams + core-java-modules/core-java-streams-2 + core-java-modules/core-java-streams-3 + + core-java-modules/core-java-function + core-java-modules/core-java-lang-math + + + core-java-modules/core-java-text + + + core-java-modules/core-java-arrays + core-java-modules/core-java-arrays-2 + core-java-modules/core-java-collections + core-java-modules/core-java-collections-2 + core-java-modules/core-java-collections-3 + core-java-modules/core-java-collections-list + core-java-modules/core-java-collections-list-2 + core-java-modules/core-java-collections-list-3 + core-java-modules/core-java-collections-array-list + core-java-modules/core-java-collections-set + core-java-modules/core-java-concurrency-basic + core-java-modules/core-java-concurrency-basic-2 + core-java-modules/core-java-concurrency-collections + core-java-modules/core-java-io + core-java-modules/core-java-io-files + core-java-modules/core-java-nio + core-java-modules/core-java-security core-java-modules/core-java-exceptions - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang-syntax-2 - core-java-modules/core-java-lang - core-java-modules/core-java-lang-2 - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules/core-java-lang-oop-3 - core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-sun - core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-scala - couchbase - custom-pmd + core-java-modules/core-java-lang-syntax + core-java-modules/core-java-lang-syntax-2 + core-java-modules/core-java-lang + core-java-modules/core-java-lang-2 + core-java-modules/core-java-lang-oop + core-java-modules/core-java-lang-oop-2 + core-java-modules/core-java-lang-oop-3 + core-java-modules + core-java-modules/core-java-networking + core-java-modules/core-java-perf + core-java-modules/core-java-sun + core-java-modules/core-java-string-conversions + core-java-modules/core-java-string-conversions-2 + core-java-modules/core-java-string-operations + core-java-modules/core-java-string-operations-2 + core-java-modules/core-java-string-algorithms + core-java-modules/core-java-string-algorithms-2 + core-java-modules/core-java-string-apis + core-scala + couchbase + custom-pmd - dagger - data-structures - ddd - deeplearning4j - disruptor - dozer - drools - dubbo + dagger + data-structures + ddd + deeplearning4j + disruptor + dozer + drools + dubbo - ethereum + ethereum - feign - flyway-cdi-extension + feign + flyway-cdi-extension - geotools - google-cloud - google-web-toolkit - - - graphql/graphql-java - grpc - gson - guava - guava-io - guava-collections - guava-collections-map + geotools + google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc + gson + guava + guava-io + guava-collections + guava-collections-map guava-collections-set - guava-modules - - guice + guava-modules + + guice - hazelcast - helidon - httpclient - httpclient-simple - hystrix + hazelcast + helidon + httpclient + httpclient-simple + hystrix - image-processing - immutables + image-processing + immutables - jackson - jackson-2 - jackson-simple - java-collections-conversions - java-collections-maps - java-collections-maps-2 - java-jdi - - java-ee-8-security-api - java-lite - java-math - java-numbers - 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 - javax-servlets - javaxval - jaxb - + java-ee-8-security-api + java-lite + java-math + java-numbers + java-numbers-2 + java-rmi + java-spi + java-strings + java-strings-2 + java-strings-ops + java-vavr-stream + java-websocket + javafx + javax-servlets + javaxval + jaxb + - jee-7-security - jee-kotlin - jersey - jgit - jgroups - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jee-kotlin + jersey + jgit + jgroups + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries + + kotlin-libraries - - libraries - libraries-data - libraries-data-2 - libraries-data-db + + libraries + libraries-data + libraries-data-2 + libraries-data-db libraries-data-io libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io - libraries-testing - libraries-security - libraries-server - libraries-http - linkrest - logging-modules - lombok - lucene + libraries-apache-commons-collections + libraries-apache-commons-io + libraries-testing + libraries-security + libraries-server + libraries-http + linkrest + logging-modules + lombok + lucene - mapstruct - - maven-all/maven - maven-all/maven-war-plugin - maven-all/profiles - maven-all/versions-maven-plugin - - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + + maven-all/maven + maven-all/maven-war-plugin + maven-all/profiles + maven-all/versions-maven-plugin + + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules + persistence-modules - rabbitmq - - ratpack - reactor-core - resteasy - restx - - rule-engines - rsocket - rxjava - rxjava-2 - oauth2-framework-impl - spf4j - spring-boot-performance - spring-boot-properties - - + rabbitmq + + ratpack + reactor-core + resteasy + restx + + rule-engines + rsocket + rxjava + rxjava-2 + oauth2-framework-impl + spf4j + spring-boot-performance + spring-boot-properties + + - + - + - - integration-lite-second + + integration-lite-second - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-2 - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito - spring-activiti - spring-akka - spring-amqp - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-5 + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-2 + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito + spring-activiti + spring-akka + spring-amqp + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-environment + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-environment spring-boot-deployment spring-boot-runtime spring-boot-runtime/disabling-console-jul spring-boot-runtime/disabling-console-log4j2 - spring-boot-runtime/disabling-console-logback - spring-boot-artifacts - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-vue + spring-boot-runtime/disabling-console-logback + spring-boot-artifacts + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-vue spring-caching - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow - spring-core - spring-core-2 - spring-core-3 + spring-core + spring-core-2 + spring-core-3 spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools - spring-di + spring-data-rest + spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools + spring-di - spring-ehcache - spring-ejb - spring-exceptions + spring-ehcache + spring-ejb + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-basics-2 + spring-mobile + spring-mockito + spring-mvc-basics-2 spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-compress - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-compress + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo - spring-scheduling + spring-scheduling spring-security-acl - spring-security-angular/server - spring-security-cache-control - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc - spring-security-mvc-socket - spring-security-openid - - spring-security-rest - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session + spring-security-angular/server + spring-security-cache-control + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc + spring-security-mvc-socket + spring-security-openid + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session spring-shell - spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + spring-sleuth + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-vault - spring-vertx + spring-vault + spring-vertx - spring-webflux-amqp + spring-webflux-amqp - spring-zuul + spring-zuul - static-analysis - stripe - structurizr - struts-2 + static-analysis + stripe + structurizr + struts-2 - testing-modules + testing-modules - twilio - twitter4j + twilio + twitter4j - undertow + undertow - vertx - vertx-and-rxjava - video-tutorials - vraptor + vertx + vertx-and-rxjava + video-tutorials + vraptor - wicket + wicket - xml - xstream - + xml + xstream + - + - - integration-heavy + + integration-heavy - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - core-java-modules/core-java - core-java-modules/core-java-concurrency-advanced + core-java-modules/core-java + core-java-modules/core-java-concurrency-advanced core-java-modules/core-java-concurrency-advanced-2 core-java-modules/core-java-concurrency-advanced-3 core-kotlin - core-kotlin-2 + core-kotlin-2 - jenkins/plugins - jhipster - jws + jenkins/plugins + jhipster + jws - libraries + libraries - persistence-modules/hibernate5 - persistence-modules/java-jpa - persistence-modules/java-jpa-2 - persistence-modules/java-mongodb - persistence-modules/jnosql + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/java-jpa-2 + persistence-modules/java-mongodb + persistence-modules/jnosql - vaadin - vavr - + vaadin + vavr + - + - + - - - - org.apache.maven.plugins - maven-jxr-plugin - ${maven-jxr-plugin.version} - - - + + + + org.apache.maven.plugins + maven-jxr-plugin + ${maven-jxr-plugin.version} + + + - - UTF-8 - UTF-8 - refs/remotes/origin/master - true - false - false - false - false + + UTF-8 + UTF-8 + refs/remotes/origin/master + true + false + false + false + false - 4.12 - 1.3 - 2.21.0 + 4.12 + 1.3 + 2.21.0 - - 1.7.21 - 1.1.7 + + 1.7.21 + 1.1.7 - - - 2.21.0 - 3.7.0 - 1.6.0 - 1.8 - 1.2.17 - 1.1 - 2.1.0.1 - 1.19 - 1.19 - 1.3 - 1.6.0 - 2.21.0 - 2.5 - 2.6 - 3.5 - 1.4 - 3.0.0 - 3.1.0 - 1.2 - 2.3.1 - 1.9.13 - 1.2 - 2.9.8 - 1.3 - 1.2.0 - 5.2.0 - 0.3.1 - 2.5.1 - 0.0.1 - 3.8 - 2.3 - - 3.8 - 1.16.12 - 1.4.197 - + + + 2.21.0 + 3.7.0 + 1.6.0 + 1.8 + 1.2.17 + 1.1 + 2.1.0.1 + 1.19 + 1.19 + 1.3 + 1.6.0 + 2.21.0 + 2.5 + 2.6 + 3.5 + 1.4 + 3.0.0 + 3.1.0 + 1.2 + 2.3.1 + 1.9.13 + 1.2 + 2.9.8 + 1.3 + 1.2.0 + 5.2.0 + 0.3.1 + 2.5.1 + 0.0.1 + 3.8 + 2.3 + + 3.8 + 1.16.12 + 1.4.197 + 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/spring-5-data-reactive/README.md b/spring-5-data-reactive/README.md index 683b493317..42fcba96f2 100644 --- a/spring-5-data-reactive/README.md +++ b/spring-5-data-reactive/README.md @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Data Reactive Repositories with MongoDB](https://www.baeldung.com/spring-data-mongodb-reactive) - [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 1724db9e66..bb308ae330 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -6,5 +6,7 @@ This module contains articles about reactive Spring 5 WebClient 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-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 7588d23304..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) 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-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 67311eed50..b3a50ad7a5 100644 --- a/spring-boot-autoconfiguration/README.md +++ b/spring-boot-autoconfiguration/README.md @@ -9,3 +9,4 @@ 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-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-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-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/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/pom.xml b/spring-cloud/pom.xml index baf86a4386..7138efc128 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -25,7 +25,7 @@ spring-cloud-zookeeper spring-cloud-gateway spring-cloud-stream - spring-cloud-stream-starters/twitterhdfs + spring-cloud-stream-starters/twitterhdfs spring-cloud-connectors-heroku spring-cloud-aws spring-cloud-consul @@ -35,9 +35,10 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - - spring-cloud-task + + spring-cloud-task spring-cloud-zuul + spring-cloud-zuul-fallback 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 new file mode 100644 index 0000000000..2f13c1923b --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Fallback for Zuul Route](TODO) diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/pom.xml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/pom.xml new file mode 100644 index 0000000000..ee0f607d8a --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + api-gateway + api-gateway + API Gateway using Zuul + jar + + + com.baeldung.spring.cloud + spring-cloud-zuul-fallback + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-zuul + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplication.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplication.java new file mode 100644 index 0000000000..78f489f2bb --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.apigateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.zuul.EnableZuulProxy; + +@SpringBootApplication +@EnableZuulProxy +public class ApiGatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(ApiGatewayApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayClientResponse.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayClientResponse.java new file mode 100644 index 0000000000..ce0c7819f1 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayClientResponse.java @@ -0,0 +1,69 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.client.ClientHttpResponse; + +public class GatewayClientResponse implements ClientHttpResponse { + + private HttpStatus status; + private String message; + + public GatewayClientResponse(HttpStatus status, String message) { + this.status = status; + this.message = message; + } + + @Override + public HttpStatus getStatusCode() throws IOException { + return status; + } + + @Override + public int getRawStatusCode() throws IOException { + return status.value(); + } + + @Override + public String getStatusText() throws IOException { + return status.getReasonPhrase(); + } + + @Override + public void close() { + } + + @Override + public InputStream getBody() throws IOException { + return new ByteArrayInputStream(message.getBytes()); + } + + @Override + public HttpHeaders getHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + return headers; + } + + public HttpStatus getStatus() { + return status; + } + + public void setStatus(HttpStatus status) { + this.status = status; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallback.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallback.java new file mode 100644 index 0000000000..73f72492c9 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallback.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@Component +class GatewayServiceFallback implements FallbackProvider { + + private static final String DEFAULT_MESSAGE = "Service not available."; + + @Override + public String getRoute() { + return "*"; // or return null; + } + + @Override + public ClientHttpResponse fallbackResponse(String route, Throwable cause) { + if (cause instanceof HystrixTimeoutException) { + return new GatewayClientResponse(HttpStatus.GATEWAY_TIMEOUT, DEFAULT_MESSAGE); + } else { + return new GatewayClientResponse(HttpStatus.INTERNAL_SERVER_ERROR, DEFAULT_MESSAGE); + } + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallback.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallback.java new file mode 100644 index 0000000000..28fb6fb6e5 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallback.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@Component +class WeatherServiceFallback implements FallbackProvider { + + private static final String DEFAULT_MESSAGE = "Weather information is not available."; + + @Override + public String getRoute() { + return "weather-service"; + } + + @Override + public ClientHttpResponse fallbackResponse(String route, Throwable cause) { + if (cause instanceof HystrixTimeoutException) { + return new GatewayClientResponse(HttpStatus.GATEWAY_TIMEOUT, DEFAULT_MESSAGE); + } else { + return new GatewayClientResponse(HttpStatus.INTERNAL_SERVER_ERROR, DEFAULT_MESSAGE); + } + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml new file mode 100644 index 0000000000..4a0662a960 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/main/resources/application.yml @@ -0,0 +1,22 @@ +spring: + application: + name: api-gateway +server: + port: 7070 + +zuul: + igoredServices: '*' + routes: + weather-service: + path: /weather/** + serviceId: weather-service + strip-prefix: false + +ribbon: + eureka: + enabled: false + +weather-service: + ribbon: + listOfServers: localhost:8080 + diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplicationIntegrationTest.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplicationIntegrationTest.java new file mode 100644 index 0000000000..4052edc1f3 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/ApiGatewayApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.apigateway; + +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 ApiGatewayApplicationIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallbackUnitTest.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallbackUnitTest.java new file mode 100644 index 0000000000..db2f703084 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/GatewayServiceFallbackUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.test.context.junit4.SpringRunner; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class GatewayServiceFallbackUnitTest { + + private static final String ROUTE = "*"; + + @Autowired + private GatewayServiceFallback fallback; + + @Test + public void testWhenGetRouteThenReturnWeatherServiceRoute() { + assertEquals(ROUTE, fallback.getRoute()); + + } + + @Test + public void testFallbackResponse_whenHystrixException_thenGatewayTimeout() throws Exception { + HystrixTimeoutException exception = new HystrixTimeoutException(); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.GATEWAY_TIMEOUT, response.getStatusCode()); + } + + @Test + public void testFallbackResponse_whenNonHystrixException_thenInternalServerError() throws Exception { + RuntimeException exception = new RuntimeException("Test exception"); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallbackUnitTest.java b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallbackUnitTest.java new file mode 100644 index 0000000000..ccd59531b5 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/java/com/baeldung/spring/cloud/apigateway/fallback/WeatherServiceFallbackUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.apigateway.fallback; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.test.context.junit4.SpringRunner; + +import com.netflix.hystrix.exception.HystrixTimeoutException; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class WeatherServiceFallbackUnitTest { + + private static final String ROUTE = "weather-service"; + + @Autowired + private WeatherServiceFallback fallback; + + @Test + public void testWhenGetRouteThenReturnWeatherServiceRoute() { + assertEquals(ROUTE, fallback.getRoute()); + + } + + @Test + public void testFallbackResponse_whenHystrixException_thenGatewayTimeout() throws Exception { + HystrixTimeoutException exception = new HystrixTimeoutException(); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.GATEWAY_TIMEOUT, response.getStatusCode()); + } + + @Test + public void testFallbackResponse_whenNonHystrixException_thenInternalServerError() throws Exception { + RuntimeException exception = new RuntimeException("Test exception"); + ClientHttpResponse response = fallback.fallbackResponse(ROUTE, exception); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/pom.xml b/spring-cloud/spring-cloud-zuul-fallback/pom.xml new file mode 100644 index 0000000000..5bdd1d49ca --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + spring-cloud-zuul-fallback + pom + spring-cloud-zuul-fallback + Spring Cloud Zuul Fallback + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + api-gateway + weather-service + + + + 1.8 + Finchley.SR2 + 3.1.1 + + diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/pom.xml b/spring-cloud/spring-cloud-zuul-fallback/weather-service/pom.xml new file mode 100644 index 0000000000..611f1dcd4f --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/pom.xml @@ -0,0 +1,39 @@ + + 4.0.0 + weather-service + Weather Service + Weather Service for Zuul Fallback Test + + + com.baeldung.spring.cloud + spring-cloud-zuul-fallback + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-starter-parent + ${spring-cloud-dependencies.version} + pom + import + + + + diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherController.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherController.java new file mode 100644 index 0000000000..3cf451dcf7 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherController.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.weatherservice; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/weather") +public class WeatherController { + + @GetMapping("/today") + public String getMessage() { + return "It's a bright sunny day today!"; + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplication.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplication.java new file mode 100644 index 0000000000..3a6d85e8d1 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.cloud.weatherservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WeatherServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(WeatherServiceApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml new file mode 100644 index 0000000000..242f842f44 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/main/resources/application.yml @@ -0,0 +1,4 @@ +spring: + application: + name: weather-service + diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherControllerIntegrationTest.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherControllerIntegrationTest.java new file mode 100644 index 0000000000..3ffd2b0e7a --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherControllerIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.cloud.weatherservice; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +@RunWith(SpringRunner.class) +@WebMvcTest(WeatherController.class) +public class WeatherControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenWeatherControllerInvoked_thenReturnWeatherInformation() throws Exception { + this.mockMvc.perform(get("/weather/today")) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("bright sunny day"))); + } + +} diff --git a/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplicationIntegrationTest.java b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplicationIntegrationTest.java new file mode 100644 index 0000000000..fec7ec1560 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/weather-service/src/test/java/com/baeldung/spring/cloud/weatherservice/WeatherServiceApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.weatherservice; + +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 WeatherServiceApplicationIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} 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 410781f2ca..941777207f 100644 --- a/spring-freemarker/README.md +++ b/spring-freemarker/README.md @@ -4,3 +4,4 @@ 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/pom.xml b/spring-integration/pom.xml index 367d25de98..f06cb91ef6 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -68,6 +68,11 @@ spring-integration-security ${spring.version} + + org.springframework.integration + spring-integration-jdbc + ${spring.version} + org.springframework.security @@ -75,6 +80,12 @@ ${spring.version} test + + + com.h2database + h2 + 1.4.197 + @@ -106,7 +117,7 @@ UTF-8 - 5.0.3.RELEASE + 5.0.13.RELEASE 1.1.4.RELEASE 1.4.7 1.1.1 diff --git a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java index 7e91345f04..e79eec3e83 100644 --- a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java +++ b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java @@ -16,8 +16,10 @@ import org.springframework.integration.core.MessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; +import org.springframework.integration.dsl.channel.MessageChannels; import org.springframework.integration.file.FileReadingMessageSource; import org.springframework.integration.file.FileWritingMessageHandler; +import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; /** @@ -104,9 +106,14 @@ public class JavaDSLFileCopyConfig { return handler; } + @Bean + public MessageChannel holdingTank() { + return MessageChannels.queue().get(); + } + // @Bean public IntegrationFlow fileReader() { - return IntegrationFlows.from(sourceDirectory()) + return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) .filter(onlyJpgs()) .channel("holdingTank") .get(); diff --git a/spring-integration/src/main/java/com/baeldung/tx/ServiceActivator.java b/spring-integration/src/main/java/com/baeldung/tx/ServiceActivator.java new file mode 100755 index 0000000000..56399c653f --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/tx/ServiceActivator.java @@ -0,0 +1,27 @@ +package com.baeldung.tx; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; + +public class ServiceActivator { + + @Autowired + private JdbcTemplate jdbcTemplate; + + private final Logger log = LoggerFactory.getLogger(this.getClass()); + + public void checkTestResults(String payload) { + + this.jdbcTemplate.update("insert into STUDENT values(?)", payload); + + if (payload.toLowerCase().startsWith("fail")) { + log.error("Service failure. Test result: {}", payload); + throw new RuntimeException("Service failure."); + } + + log.info("Service success. Test result: {}", payload); + } + +} diff --git a/spring-integration/src/main/java/com/baeldung/tx/TxIntegrationConfig.java b/spring-integration/src/main/java/com/baeldung/tx/TxIntegrationConfig.java new file mode 100644 index 0000000000..7a58cb3125 --- /dev/null +++ b/spring-integration/src/main/java/com/baeldung/tx/TxIntegrationConfig.java @@ -0,0 +1,155 @@ +package com.baeldung.tx; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.integration.annotation.InboundChannelAdapter; +import org.springframework.integration.annotation.Poller; +import org.springframework.integration.annotation.ServiceActivator; +import org.springframework.integration.annotation.Transformer; +import org.springframework.integration.channel.DirectChannel; +import org.springframework.integration.config.EnableIntegration; +import org.springframework.integration.core.MessageSource; +import org.springframework.integration.dsl.Pollers; +import org.springframework.integration.file.FileReadingMessageSource; +import org.springframework.integration.file.filters.SimplePatternFileListFilter; +import org.springframework.integration.file.transformer.FileToStringTransformer; +import org.springframework.integration.scheduling.PollerMetadata; +import org.springframework.integration.transaction.*; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.messaging.MessageChannel; +import org.springframework.transaction.interceptor.TransactionInterceptor; + +import javax.sql.DataSource; +import java.io.File; +import java.util.Scanner; + +@Configuration +@EnableIntegration +public class TxIntegrationConfig { + + private final Logger log = LoggerFactory.getLogger(this.getClass()); + + public final String INPUT_DIR = System.getProperty("java.io.tmpdir") + "/tx/"; + public final String FILE_PATTERN = "*.txt"; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Autowired + private DataSource dataSource; + + @Autowired + private TransactionSynchronizationFactory transactionSynchronizationFactory; + + @Autowired + DataSourceTransactionManager txManager; + + @Bean + public MessageChannel inputChannel() { + return new DirectChannel(); + } + + @Bean + @InboundChannelAdapter(value = "inputChannel", poller = @Poller(value = "pollerMetadata")) + public MessageSource fileReadingMessageSource() { + FileReadingMessageSource sourceReader = new FileReadingMessageSource(); + sourceReader.setDirectory(new File(INPUT_DIR)); + sourceReader.setFilter(new SimplePatternFileListFilter(FILE_PATTERN)); + return sourceReader; + } + + @Bean + public PollerMetadata pollerMetadata() { + return Pollers.fixedDelay(5000) + .advice(transactionInterceptor()) + .transactionSynchronizationFactory(transactionSynchronizationFactory) + .get(); + } + + private TransactionInterceptor transactionInterceptor() { + return new TransactionInterceptorBuilder().transactionManager(txManager).build(); + } + + @Bean + public TransactionSynchronizationFactory transactionSynchronizationFactory() { + ExpressionEvaluatingTransactionSynchronizationProcessor processor = + new ExpressionEvaluatingTransactionSynchronizationProcessor(); + + SpelExpressionParser spelParser = new SpelExpressionParser(); + processor.setAfterCommitExpression( + spelParser.parseExpression( + "payload.renameTo(new java.io.File(payload.absolutePath + '.PASSED'))")); + processor.setAfterRollbackExpression( + spelParser.parseExpression( + "payload.renameTo(new java.io.File(payload.absolutePath + '.FAILED'))")); + + return new DefaultTransactionSynchronizationFactory(processor); + } + + @Bean + @Transformer(inputChannel = "inputChannel", outputChannel = "toServiceChannel") + public FileToStringTransformer fileToStringTransformer() { + return new FileToStringTransformer(); + } + + @ServiceActivator(inputChannel = "toServiceChannel") + public void serviceActivator(String payload) { + + jdbcTemplate.update("insert into STUDENT values(?)", payload); + + if (payload.toLowerCase().startsWith("fail")) { + log.error("Service failure. Test result: {} ", payload); + throw new RuntimeException("Service failure."); + } + + log.info("Service success. Test result: {}", payload); + } + + @Bean + public JdbcTemplate jdbcTemplate(DataSource dataSource) { + return new JdbcTemplate(dataSource); + } + + @Bean + public DataSource dataSource() { + return new EmbeddedDatabaseBuilder() + .setType(EmbeddedDatabaseType.H2) + .addScript("classpath:table.sql") + .build(); + } + + @Bean + public DataSourceTransactionManager txManager() { + return new DataSourceTransactionManager(dataSource); + } + + public static void main(final String... args) { + final AbstractApplicationContext context = new AnnotationConfigApplicationContext(TxIntegrationConfig.class); + context.registerShutdownHook(); + + final Scanner scanner = new Scanner(System.in); + System.out.print("Integration flow is running. Type q + to quit "); + while (true) { + final String input = scanner.nextLine(); + if ("q".equals(input.trim())) { + context.close(); + scanner.close(); + break; + } + } + System.exit(0); + } + +} + + + diff --git a/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-tx-context.xml b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-tx-context.xml new file mode 100755 index 0000000000..2861826521 --- /dev/null +++ b/spring-integration/src/main/resources/META-INF/spring/integration/spring-integration-tx-context.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-integration/src/main/resources/table.sql b/spring-integration/src/main/resources/table.sql new file mode 100644 index 0000000000..9ca58f6f27 --- /dev/null +++ b/spring-integration/src/main/resources/table.sql @@ -0,0 +1,4 @@ + +CREATE TABLE IF NOT EXISTS STUDENT ( + TEST VARCHAR(256) +); \ No newline at end of file diff --git a/spring-integration/src/test/java/com/baeldung/tx/TxIntegrationTest.java b/spring-integration/src/test/java/com/baeldung/tx/TxIntegrationTest.java new file mode 100644 index 0000000000..1bbd16aa4b --- /dev/null +++ b/spring-integration/src/test/java/com/baeldung/tx/TxIntegrationTest.java @@ -0,0 +1,56 @@ +package com.baeldung.tx; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +public final class TxIntegrationTest { + + private static final String CONTEXT_CONFIG = "classpath:META-INF/spring/integration/spring-integration-tx-context.xml"; + + @Test + public void whenFileDoesntStartWithFail_thenTxSuccessful() throws InterruptedException, IOException { + final AbstractApplicationContext context = + new ClassPathXmlApplicationContext(CONTEXT_CONFIG); + + String fileName = System.getProperty("java.io.tmpdir") + "/tx/test1.txt"; + FileWriter fw = new FileWriter(fileName); + fw.write("PASSED!"); + fw.close(); + + context.registerShutdownHook(); + Thread.sleep(5000); + + File file = new File(fileName + ".PASSED"); + Assert.assertTrue(file.exists()); + } + + @Test + public void whenFileStartsWithFail_thenTxFailed() { + + String fileName = System.getProperty("java.io.tmpdir") + "/tx/test2.txt"; + + try { + final AbstractApplicationContext context = + new ClassPathXmlApplicationContext(CONTEXT_CONFIG); + + FileWriter fw = new FileWriter(fileName); + fw.write("FAILED!"); + fw.close(); + + context.registerShutdownHook(); + Thread.sleep(5000); + } catch (Exception e) { + // Exception is expected, do nothing + } + + File file = new File(fileName + ".FAILED"); + Assert.assertTrue(file.exists()); + } + +} 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-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java index 8312f20c05..26c061e9cd 100644 --- a/spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java +++ b/spring-jooq/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java @@ -12,7 +12,7 @@ public class ExceptionTranslator extends DefaultExecuteListener { @Override public void exception(ExecuteContext context) { SQLDialect dialect = context.configuration().dialect(); - SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(dialect.name()); + SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(dialect.thirdParty().springDbName()); context.exception(translator.translate("Access database using jOOQ", context.sql(), context.sqlException())); } diff --git a/spring-mvc-simple-2/README.md b/spring-mvc-simple-2/README.md index a4a545ab72..cff8891a1a 100644 --- a/spring-mvc-simple-2/README.md +++ b/spring-mvc-simple-2/README.md @@ -5,4 +5,9 @@ This module contains articles about Spring MVC ## Relevant articles: - [How to Read HTTP Headers in Spring REST Controllers](https://www.baeldung.com/spring-rest-http-headers) - [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder) +- [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) +- [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation) +- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url) +- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param) +- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) - More articles: [[<-- prev]](/spring-mvc-simple) diff --git a/spring-mvc-simple-2/src/main/resources/application.properties b/spring-mvc-simple-2/src/main/resources/application.properties index 709574239b..d29338d3d3 100644 --- a/spring-mvc-simple-2/src/main/resources/application.properties +++ b/spring-mvc-simple-2/src/main/resources/application.properties @@ -1 +1,3 @@ -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 \ No newline at end of file diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index b6a34475ea..44a20e1527 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -14,6 +14,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) - [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable) +- [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error) ## Spring MVC with XML Configuration Example Project - access a sample jsp page at: `http://localhost:8080/spring-mvc-xml/sample.html` diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index 5bc3a70ed5..a2736ba03c 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -125,6 +125,7 @@ xml-apis xml-apis + ${xml-apis.version} org.javassist @@ -284,6 +285,7 @@ 1.4.9 + 1.4.01 19.0 @@ -294,4 +296,4 @@ 1.1.3 - \ No newline at end of file + diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 7ee658d8ba..293bac9479 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -144,6 +144,7 @@ xml-apis xml-apis + ${xml-apis.version} org.javassist @@ -350,6 +351,7 @@ 1.4.9 3.21.0-GA + 1.4.01 19.0 @@ -359,4 +361,4 @@ 1.1.3 - \ No newline at end of file + diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index 9ef8ed0584..1fba4bc242 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -16,4 +16,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using the Spring RestTemplate Interceptor](https://www.baeldung.com/spring-rest-template-interceptor) - [Uploading MultipartFile with Spring RestTemplate](https://www.baeldung.com/spring-rest-template-multipart-upload) - [Get and Post Lists of Objects with RestTemplate](https://www.baeldung.com/spring-rest-template-list) -- [Introduction to FindBugs](https://www.baeldung.com/intro-to-findbugs) \ No newline at end of file +- [Introduction to FindBugs](https://www.baeldung.com/intro-to-findbugs) +- [Copy of RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json-test) diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index 191719b084..49e375f9cc 100644 --- a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java +++ b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -1,24 +1,27 @@ package com.baeldung.resttemplate.lists.client; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; -import org.springframework.web.client.RestTemplate; - import com.baeldung.resttemplate.lists.dto.Employee; import com.baeldung.resttemplate.lists.dto.EmployeeList; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.List; +import static java.util.Arrays.asList; + /** * Application that shows how to use Lists with RestTemplate. */ -public class EmployeeClient -{ - public static void main(String[] args) - { +public class EmployeeClient { + public static void main(String[] args) { EmployeeClient employeeClient = new EmployeeClient(); + System.out.println("Calling GET for entity using arrays"); + employeeClient.getForEntityEmployeesAsArray(); + System.out.println("Calling GET using ParameterizedTypeReference"); employeeClient.getAllEmployeesUsingParameterizedTypeReference(); @@ -32,13 +35,30 @@ public class EmployeeClient employeeClient.createEmployeesUsingWrapperClass(); } - public EmployeeClient() - { + public EmployeeClient() { } - public List getAllEmployeesUsingParameterizedTypeReference() - { + public Employee[] getForEntityEmployeesAsArray() { + + RestTemplate restTemplate = new RestTemplate(); + + ResponseEntity response = + restTemplate.getForEntity( + "http://localhost:8082/spring-rest/employees/", + Employee[].class); + + Employee[] employees = response.getBody(); + + assert employees != null; + asList(employees).forEach(System.out::println); + + return employees; + + } + + + public List getAllEmployeesUsingParameterizedTypeReference() { RestTemplate restTemplate = new RestTemplate(); ResponseEntity> response = @@ -46,17 +66,18 @@ public class EmployeeClient "http://localhost:8082/spring-rest/employees/", HttpMethod.GET, null, - new ParameterizedTypeReference>(){}); + new ParameterizedTypeReference>() { + }); List employees = response.getBody(); - employees.forEach(e -> System.out.println(e)); + assert employees != null; + employees.forEach(System.out::println); return employees; } - public List getAllEmployeesUsingWrapperClass() - { + public List getAllEmployeesUsingWrapperClass() { RestTemplate restTemplate = new RestTemplate(); EmployeeList response = @@ -66,13 +87,12 @@ public class EmployeeClient List employees = response.getEmployees(); - employees.forEach(e -> System.out.println(e)); + employees.forEach(System.out::println); return employees; } - public void createEmployeesUsingLists() - { + public void createEmployeesUsingLists() { RestTemplate restTemplate = new RestTemplate(); List newEmployees = new ArrayList<>(); @@ -85,8 +105,7 @@ public class EmployeeClient ResponseEntity.class); } - public void createEmployeesUsingWrapperClass() - { + public void createEmployeesUsingWrapperClass() { RestTemplate restTemplate = new RestTemplate(); List newEmployees = new ArrayList<>(); diff --git a/spring-scheduling/README.md b/spring-scheduling/README.md index 72d5a7dc83..2e3bb2b5e5 100644 --- a/spring-scheduling/README.md +++ b/spring-scheduling/README.md @@ -1,5 +1,6 @@ ### Relevant articles: - [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler) +- [The @Scheduled Annotation in Spring](https://www.baeldung.com/spring-scheduled-tasks) - [Guide to Spring Retry](http://www.baeldung.com/spring-retry) - [How To Do @Async in Spring](http://www.baeldung.com/spring-async) diff --git a/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java b/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java index 284bcf5e6a..23bbee3bc3 100644 --- a/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java +++ b/spring-scheduling/src/main/java/org/baeldung/scheduling/ScheduledAnnotationExample.java @@ -31,9 +31,10 @@ public class ScheduledAnnotationExample { System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000); } - @Scheduled(fixedDelay = 1000, initialDelay = 100) + @Scheduled(fixedDelay = 1000, initialDelay = 1000) public void scheduleFixedRateWithInitialDelayTask() { - System.out.println("Fixed delay task with one second initial delay - " + System.currentTimeMillis() / 1000); + long now = System.currentTimeMillis() / 1000; + System.out.println("Fixed rate task with one second initial delay - " + now); } /** @@ -41,7 +42,8 @@ public class ScheduledAnnotationExample { */ @Scheduled(cron = "0 15 10 15 * ?") public void scheduleTaskUsingCronExpression() { - System.out.println("schedule tasks using cron expressions - " + System.currentTimeMillis() / 1000); + long now = System.currentTimeMillis() / 1000; + System.out.println("schedule tasks using cron jobs - " + now); } @Scheduled(cron = "${cron.expression}") diff --git a/spring-scheduling/src/main/resources/springScheduled-config.xml b/spring-scheduling/src/main/resources/springScheduled-config.xml index d1ff9dc028..4078f535da 100644 --- a/spring-scheduling/src/main/resources/springScheduled-config.xml +++ b/spring-scheduling/src/main/resources/springScheduled-config.xml @@ -15,7 +15,7 @@ - + diff --git a/spring-security-mvc-boot/README.md b/spring-security-mvc-boot/README.md index 7dcfe4d70f..a1056cc130 100644 --- a/spring-security-mvc-boot/README.md +++ b/spring-security-mvc-boot/README.md @@ -17,3 +17,5 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Spring Security – Whitelist IP Range](https://www.baeldung.com/spring-security-whitelist-ip-range) - [Find the Registered Spring Security Filters](https://www.baeldung.com/spring-security-registered-filters) - [HTTPS using Self-Signed Certificate in Spring Boot](https://www.baeldung.com/spring-boot-https-self-signed-certificate) +- [Spring Security: Exploring JDBC Authentication](https://www.baeldung.com/spring-security-jdbc-authentication) + diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/README.md b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/README.md deleted file mode 100644 index a7cdfec7d8..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Spring Security: Exploring JDBC Authentication](https://www.baeldung.com/spring-security-jdbc-authentication) diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/bean/Constants.java b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Constants.java new file mode 100644 index 0000000000..bf204c3b99 --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Constants.java @@ -0,0 +1,5 @@ +package com.baeldung.session.bean; + +public class Constants { + public static final String FOO = "foo"; +} diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/bean/Foo.java b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Foo.java new file mode 100644 index 0000000000..c9c9c011d4 --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/session/bean/Foo.java @@ -0,0 +1,29 @@ +package com.baeldung.session.bean; + +import static org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS; +import static org.springframework.web.context.WebApplicationContext.SCOPE_SESSION; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(value = SCOPE_SESSION, proxyMode = TARGET_CLASS) +public class Foo { + private final String created; + + public Foo() { + this.created = LocalDateTime.now() + .format(DateTimeFormatter.ISO_DATE_TIME); + } + + public Foo(Foo theFoo) { + this.created = theFoo.created; + } + + public String getCreated() { + return created; + } +} diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java b/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java index 35b53a0e7f..9a4978c27e 100644 --- a/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java +++ b/spring-security-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java @@ -38,7 +38,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .csrf().disable() .authorizeRequests() .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*","/invalidSession*", "/sessionExpired*").permitAll() + .antMatchers("/login*","/invalidSession*", "/sessionExpired*", "/foo/**").permitAll() .anyRequest().authenticated() .and() .formLogin() diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/web/FooController.java b/spring-security-mvc/src/main/java/com/baeldung/session/web/FooController.java new file mode 100644 index 0000000000..7c3385dcbd --- /dev/null +++ b/spring-security-mvc/src/main/java/com/baeldung/session/web/FooController.java @@ -0,0 +1,44 @@ +package com.baeldung.session.web; + +import javax.servlet.http.HttpSession; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import com.baeldung.session.bean.Constants; +import com.baeldung.session.bean.Foo; + +@RestController +@RequestMapping(path = "/foo") +public class FooController { + + @Autowired + private Foo theFoo; + + @GetMapping(path = "set") + public void fooSet(HttpSession session) { + session.setAttribute(Constants.FOO, new Foo()); + } + + @GetMapping(path = "autowired") + public Foo getAutowired() { + return new Foo(theFoo); + } + + @GetMapping(path = "inject") + public Foo fooInject(HttpSession session) { + return (Foo) session.getAttribute(Constants.FOO); + } + + @GetMapping(path = "raw") + public Foo fromRaw() { + ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + HttpSession session = attr.getRequest() + .getSession(true); + return (Foo) session.getAttribute(Constants.FOO); + } +} diff --git a/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java b/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java index 82199a9e4e..79f57246a9 100644 --- a/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java +++ b/spring-security-mvc/src/main/java/com/baeldung/session/web/SessionRestController.java @@ -3,15 +3,13 @@ package com.baeldung.session.web; import javax.servlet.http.HttpSession; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class SessionRestController { @GetMapping("/session-max-interval") - @ResponseBody - public String retrieveMaxSessionIncativeInterval(HttpSession session) { + public String retrieveMaxSessionInactiveInterval(HttpSession session) { return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval(); } } diff --git a/spring-security-mvc/src/main/resources/application.properties b/spring-security-mvc/src/main/resources/application.properties index 56b2b7b123..6f0d0519ef 100644 --- a/spring-security-mvc/src/main/resources/application.properties +++ b/spring-security-mvc/src/main/resources/application.properties @@ -1,3 +1,5 @@ +spring.jackson.serialization.fail-on-empty-beans=false + server.servlet.session.timeout=65s spring.mvc.view.prefix=/WEB-INF/view/ diff --git a/spring-security-mvc/src/main/resources/webSecurityConfig.xml b/spring-security-mvc/src/main/resources/webSecurityConfig.xml index 42ff4c2186..e91755d394 100644 --- a/spring-security-mvc/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc/src/main/resources/webSecurityConfig.xml @@ -7,7 +7,7 @@ http://www.springframework.org/schema/beans/spring-beans.xsd" > - + @@ -22,10 +22,9 @@ - - + diff --git a/spring-security-mvc/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc/src/main/webapp/WEB-INF/web.xml index 2ef734441b..88087c92ed 100644 --- a/spring-security-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-security-mvc/src/main/webapp/WEB-INF/web.xml @@ -8,13 +8,14 @@ 1 + COOKIE - org.baeldung.web.SessionListenerWithMetrics + com.baeldung.web.SessionListenerWithMetrics ]](/spring-thymeleaf-2) ### Build the Project @@ -35,7 +30,6 @@ Access the pages using the URLs: - http://localhost:8082/spring-thymeleaf/ - http://localhost:8082/spring-thymeleaf/addStudent/ - http://localhost:8082/spring-thymeleaf/listStudents/ - - http://localhost:8082/spring-thymeleaf/booleans/ The first URL is the home page of the application. The home page has links to the second and third pages. diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index cdc2ed25ae..d260a78d76 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -141,26 +141,6 @@ - - org.apache.tomcat.maven - tomcat7-maven-plugin - ${tomcat7-maven-plugin.version} - - - tomcat-run - - exec-war-only - - package - - / - false - webapp.jar - utf-8 - - - - @@ -174,7 +154,6 @@ 1.6.1 - 2.2 diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/WorkingWithArraysInThymeleafApplication.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/WorkingWithArraysInThymeleafApplication.java deleted file mode 100644 index bce0660fda..0000000000 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/WorkingWithArraysInThymeleafApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -// package com.baeldung.thymeleaf; - -// import org.springframework.boot.SpringApplication; -// import org.springframework.boot.autoconfigure.SpringBootApplication; - -// @SpringBootApplication -// public class WorkingWithArraysInThymeleafApplication { - -// public static void main(String[] args) { -// SpringApplication.run(WorkingWithArraysInThymeleafApplication.class, args); -// } -// } diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html index 25ff6a19bb..b458f7270c 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html @@ -24,9 +24,6 @@ - - - diff --git a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextIntegrationTest.java similarity index 95% rename from spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextIntegrationTest.java index c7a0b4fc60..9a066b3101 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextIntegrationTest.java @@ -1,15 +1,14 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +package com.baeldung.thymeleaf; import com.baeldung.thymeleaf.config.InitSecurity; import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import com.baeldung.thymeleaf.config.WebMVCSecurity; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java similarity index 95% rename from spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java rename to spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java index 1ff1c52c68..cbd3f85b48 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/SpringContextTest.java @@ -1,15 +1,14 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +package com.baeldung.thymeleaf; import com.baeldung.thymeleaf.config.InitSecurity; import com.baeldung.thymeleaf.config.WebApp; import com.baeldung.thymeleaf.config.WebMVCConfig; import com.baeldung.thymeleaf.config.WebMVCSecurity; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java similarity index 98% rename from spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java rename to spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java index 4f6480e3b2..a7c9fb4ae4 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/security/csrf/CsrfEnabledIntegrationTest.java @@ -1,12 +1,9 @@ -package org.baeldung.security.csrf; - -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -import javax.servlet.Filter; +package com.baeldung.thymeleaf.security.csrf; +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,10 +18,12 @@ import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.thymeleaf.config.InitSecurity; -import com.baeldung.thymeleaf.config.WebApp; -import com.baeldung.thymeleaf.config.WebMVCConfig; -import com.baeldung.thymeleaf.config.WebMVCSecurity; +import javax.servlet.Filter; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration diff --git a/testing-modules/hamcrest/README.md b/testing-modules/hamcrest/README.md index f2ff6b996d..cc1eeb3fbb 100644 --- a/testing-modules/hamcrest/README.md +++ b/testing-modules/hamcrest/README.md @@ -7,6 +7,6 @@ This module contains articles about Hamcrest - [Hamcrest File Matchers](https://www.baeldung.com/hamcrest-file-matchers) - [Hamcrest Object Matchers](https://www.baeldung.com/hamcrest-object-matchers) - [Hamcrest Bean Matchers](https://www.baeldung.com/hamcrest-bean-matchers) -- [Hamcrest Number Matchers](https://www.baeldung.com/hamcrest-number-matchers) +- [Using Hamcrest Number Matchers](https://www.baeldung.com/hamcrest-number-matchers) - [Hamcrest Common Core Matchers](https://www.baeldung.com/hamcrest-core-matchers) - [Hamcrest Custom Matchers](https://www.baeldung.com/hamcrest-custom-matchers) diff --git a/testing-modules/junit-4/README.md b/testing-modules/junit-4/README.md index d19a0a1e47..6cc3981ed4 100644 --- a/testing-modules/junit-4/README.md +++ b/testing-modules/junit-4/README.md @@ -4,3 +4,4 @@ - [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners) - [Introduction to JUnitParams](http://www.baeldung.com/junit-params) - [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) +- [Introduction to Lambda Behave](https://www.baeldung.com/lambda-behave) diff --git a/testing-modules/junit-5-advanced/README.md b/testing-modules/junit-5-advanced/README.md index 61a65b2e5a..4a31292683 100644 --- a/testing-modules/junit-5-advanced/README.md +++ b/testing-modules/junit-5-advanced/README.md @@ -2,3 +2,4 @@ - [JUnit 5 TestWatcher API](https://www.baeldung.com/junit-testwatcher) - [JUnit Custom Display Name Generator API](https://www.baeldung.com/junit-custom-display-name-generator) +- [@TestInstance Annotation in JUnit 5](https://www.baeldung.com/junit-testinstance-annotation) diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index 2c53657481..8441eb3db7 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -7,10 +7,10 @@ load-testing-comparison - parent-modules + parent-boot-2 com.baeldung - 1.0.0-SNAPSHOT - ../../pom.xml + 0.0.1-SNAPSHOT + ../../parent-boot-2 @@ -34,11 +34,6 @@ scala-library ${scala.version} - - - - - com.fasterxml.jackson.core jackson-databind @@ -47,33 +42,22 @@ org.springframework.boot spring-boot-starter - ${spring.boot.version} org.springframework.boot spring-boot-starter-web - ${spring.boot.version} org.springframework.boot spring-boot-starter-data-jpa - ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-test - ${spring.boot.version} - test com.h2database h2 - ${h2.version} org.projectlombok lombok - ${lombok.version} compile @@ -143,8 +127,6 @@ 3.2.2 2.2.1 5.0 - 3.11 - 2.0.5.RELEASE - \ No newline at end of file + diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 6b8f53ffee..7cef9ee8f6 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -14,3 +14,5 @@ - [Mocking Void Methods with Mockito](https://www.baeldung.com/mockito-void-methods) - [Mock Final Classes and Methods with Mockito](https://www.baeldung.com/mockito-final) - [Testing Callbacks with Mockito](https://www.baeldung.com/mockito-callbacks) +- [Mockito – Using Spies](https://www.baeldung.com/mockito-spy) +- [Quick Guide to BDDMockito](https://www.baeldung.com/bdd-mockito) diff --git a/testing-modules/mocks/README.md b/testing-modules/mocks/README.md index 3baefe072b..fc7ec49e8b 100644 --- a/testing-modules/mocks/README.md +++ b/testing-modules/mocks/README.md @@ -9,3 +9,4 @@ - [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) - [Introduction to Jukito](http://www.baeldung.com/jukito) - [A Guide to JavaFaker](https://www.baeldung.com/java-faker) +- [File System Mocking with Jimfs](https://www.baeldung.com/jimfs-file-system-mocking) diff --git a/testing-modules/mocks/pom.xml b/testing-modules/mocks/pom.xml index bf75cfc3a2..cbda386af8 100644 --- a/testing-modules/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -1,55 +1,62 @@ - - 4.0.0 - mocks - mocks - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - - - - - com.github.javafaker - javafaker - ${javafaker.version} - - - org.jmockit - jmockit - ${jmockit.version} - test - - - org.jukito - jukito - ${jukito.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - - org.easymock - easymock - ${easymock.version} - test - - - - - 0.15 - 1.5 -2.21.0 - 3.5.1 - 1.41 - - - + + 4.0.0 + mocks + mocks + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + com.github.javafaker + javafaker + ${javafaker.version} + + + org.jmockit + jmockit + ${jmockit.version} + test + + + org.jukito + jukito + ${jukito.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.easymock + easymock + ${easymock.version} + test + + + + com.google.jimfs + jimfs + ${jimf.version} + + + + + 0.15 + 1.5 + 2.21.0 + 3.5.1 + 1.41 + 1.1 + + + diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileManipulation.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileManipulation.java new file mode 100644 index 0000000000..ae163b094f --- /dev/null +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileManipulation.java @@ -0,0 +1,19 @@ +package com.baeldung.jimfs; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +public class FileManipulation { + + void move(final Path origin, final Path destination) { + try { + Files.createDirectories(destination); + Files.move(origin, destination, StandardCopyOption.REPLACE_EXISTING); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } +} diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java new file mode 100644 index 0000000000..9c5371910e --- /dev/null +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FilePathReader.java @@ -0,0 +1,18 @@ +package com.baeldung.jimfs; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Path; + +class FilePathReader { + + String getSystemPath(final Path path) { + try { + return path + .toRealPath() + .toString(); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } +} diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java new file mode 100644 index 0000000000..55bd87ee81 --- /dev/null +++ b/testing-modules/mocks/src/main/java/com/baeldung/jimfs/FileRepository.java @@ -0,0 +1,43 @@ +package com.baeldung.jimfs; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class FileRepository { + + void create(final Path path, final String fileName) { + final Path filePath = path.resolve(fileName); + try { + Files.createFile(filePath); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } + + String read(final Path path) { + try { + return new String(Files.readAllBytes(path)); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } + + String update(final Path path, final String newContent) { + try { + Files.write(path, newContent.getBytes()); + return newContent; + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } + + void delete(final Path path) { + try { + Files.deleteIfExists(path); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } +} diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java new file mode 100644 index 0000000000..05f3405e57 --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileManipulationUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.jimfs; + +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class FileManipulationUnitTest implements FileTestProvider { + + private final FileManipulation fileManipulation = new FileManipulation(); + + private static Stream provideFileSystem() { + return Stream.of(Arguments.of(Jimfs.newFileSystem(Configuration.unix())), Arguments.of(Jimfs.newFileSystem(Configuration.windows())), Arguments.of(Jimfs.newFileSystem(Configuration.osX()))); + } + + @ParameterizedTest + @DisplayName("Should move file to new destination") + @MethodSource("provideFileSystem") + void givenEachSystem_whenMovingFile_thenMovedToNewPath(final FileSystem fileSystem) throws Exception { + final Path origin = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), origin); + final Path destination = fileSystem.getPath("newDirectory", RESOURCE_FILE_NAME); + + fileManipulation.move(origin, destination); + + assertFalse(Files.exists(origin)); + assertTrue(Files.exists(destination)); + } +} \ No newline at end of file diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java new file mode 100644 index 0000000000..f95b76a86d --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FilePathReaderUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.jimfs; + +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class FilePathReaderUnitTest { + + private static final String DIRECTORY_NAME = "baeldung"; + + private final FilePathReader filePathReader = new FilePathReader(); + + @Test + @DisplayName("Should get path on windows") + void givenWindowsSystem_shouldGetPath_thenReturnWindowsPath() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); + final Path path = getPathToFile(fileSystem); + + final String stringPath = filePathReader.getSystemPath(path); + + assertEquals("C:\\work\\" + DIRECTORY_NAME, stringPath); + } + + @Test + @DisplayName("Should get path on unix") + void givenUnixSystem_shouldGetPath_thenReturnUnixPath() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); + final Path path = getPathToFile(fileSystem); + + final String stringPath = filePathReader.getSystemPath(path); + + assertEquals("/work/" + DIRECTORY_NAME, stringPath); + } + + private Path getPathToFile(final FileSystem fileSystem) throws Exception { + final Path path = fileSystem.getPath(DIRECTORY_NAME); + Files.createDirectory(path); + + return path; + } +} \ No newline at end of file diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java new file mode 100644 index 0000000000..c72c2f1a1f --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileRepositoryUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.jimfs; + +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +class FileRepositoryUnitTest implements FileTestProvider { + + private final FileRepository fileRepository = new FileRepository(); + + @Test + @DisplayName("Should create a file on a file system") + void givenUnixSystem_whenCreatingFile_thenCreatedInPath() { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); + final String fileName = "newFile.txt"; + final Path pathToStore = fileSystem.getPath(""); + + fileRepository.create(pathToStore, fileName); + + assertTrue(Files.exists(pathToStore.resolve(fileName))); + } + + @Test + @DisplayName("Should read the content of the file") + void givenOSXSystem_whenReadingFile_thenContentIsReturned() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.osX()); + final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), resourceFilePath); + + final String content = fileRepository.read(resourceFilePath); + + assertEquals(FILE_CONTENT, content); + } + + @Test + @DisplayName("Should update the content of the file") + void givenWindowsSystem_whenUpdatingFile_thenContentHasChanged() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.windows()); + final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), resourceFilePath); + final String newContent = "I'm updating you."; + + final String content = fileRepository.update(resourceFilePath, newContent); + + assertEquals(newContent, content); + assertEquals(newContent, fileRepository.read(resourceFilePath)); + } + + @Test + @DisplayName("Should delete file") + void givenCurrentSystem_whenDeletingFile_thenFileHasBeenDeleted() throws Exception { + final FileSystem fileSystem = Jimfs.newFileSystem(); + final Path resourceFilePath = fileSystem.getPath(RESOURCE_FILE_NAME); + Files.copy(getResourceFilePath(), resourceFilePath); + + fileRepository.delete(resourceFilePath); + + assertFalse(Files.exists(resourceFilePath)); + } +} \ No newline at end of file diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileTestProvider.java b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileTestProvider.java new file mode 100644 index 0000000000..51b584ee8c --- /dev/null +++ b/testing-modules/mocks/src/test/java/com/baeldung/jimfs/FileTestProvider.java @@ -0,0 +1,16 @@ +package com.baeldung.jimfs; + +import java.nio.file.Path; +import java.nio.file.Paths; + +public interface FileTestProvider { + String FILE_CONTENT = "I'm the file content."; + String RESOURCE_FILE_NAME = "fileRepositoryRead.txt"; + + default Path getResourceFilePath() { + final String resourceFilePath = getClass() + .getResource("/" + RESOURCE_FILE_NAME) + .getPath(); + return Paths.get(resourceFilePath); + } +} diff --git a/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt b/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt new file mode 100644 index 0000000000..b63f63cdd6 --- /dev/null +++ b/testing-modules/mocks/src/test/resources/fileRepositoryRead.txt @@ -0,0 +1 @@ +I'm the file content. \ No newline at end of file diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index 1b06c13953..2427dfabbe 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -6,3 +6,4 @@ - [How to Test the @Scheduled Annotation](https://www.baeldung.com/spring-testing-scheduled-annotation) - [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized) - [Override Properties in Spring’s Tests](https://www.baeldung.com/spring-tests-override-properties) +- [A Quick Guide to @DirtiesContext](https://www.baeldung.com/spring-dirtiescontext) diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 8a76dc903c..15431cfb77 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -84,6 +84,11 @@ ${junit.jupiter.version} test + + org.junit.platform + junit-platform-commons + ${junit.commons.version} + org.awaitility awaitility @@ -112,7 +117,8 @@ 2.0.0.0 3.1.6 - 5.4.0 + 5.5.0 + 1.5.2 5.1.4.RELEASE 4.0.1 2.1.1 diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java index f3e7b8c228..7afd4a22d4 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/dirtiescontext/DirtiesContextIntegrationTest.java @@ -10,10 +10,12 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.MethodMode; import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; @TestMethodOrder(OrderAnnotation.class) @ExtendWith(SpringExtension.class) @SpringBootTest(classes = SpringDataRestApplication.class) +@EnableWebMvc class DirtiesContextIntegrationTest { @Autowired diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java index 95d83420b7..815b628f0a 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java @@ -1,21 +1,25 @@ package com.baeldung.overrideproperties; -import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertEquals; +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") +@EnableWebMvc public class ProfilePropertySourceResolverIntegrationTest { - @Autowired private PropertySourceResolver propertySourceResolver; + @Autowired + private PropertySourceResolver propertySourceResolver; @Test public void shouldProfiledProperty_overridePropertyValues() { diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java index 573a46dd5f..d00aa51e6c 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java @@ -1,18 +1,22 @@ package com.baeldung.overrideproperties; -import com.baeldung.overrideproperties.resolver.PropertySourceResolver; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; @RunWith(SpringRunner.class) @SpringBootTest(properties = { "example.firstProperty=annotation" }) +@EnableWebMvc public class SpringBootPropertySourceResolverIntegrationTest { - @Autowired private PropertySourceResolver propertySourceResolver; + @Autowired + private PropertySourceResolver propertySourceResolver; @Test public void shouldSpringBootTestAnnotation_overridePropertyValues() { diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java index c724713854..dc15851277 100644 --- a/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java @@ -1,19 +1,23 @@ package com.baeldung.overrideproperties; -import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.junit.Assert.assertEquals; +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; @RunWith(SpringRunner.class) @SpringBootTest +@EnableWebMvc public class TestResourcePropertySourceResolverIntegrationTest { - @Autowired private PropertySourceResolver propertySourceResolver; + @Autowired + private PropertySourceResolver propertySourceResolver; @Test public void shouldTestResourceFile_overridePropertyValues() { diff --git a/vaadin/README.md b/vaadin/README.md index 1d570d1f58..92ee8b938e 100644 --- a/vaadin/README.md +++ b/vaadin/README.md @@ -1,4 +1,8 @@ -## Relevant articles: +## Vaadin + +This module contains articles about Vaadin. + +### Relevant articles: - [Introduction to Vaadin](https://www.baeldung.com/vaadin) - [Sample Application with Spring Boot and Vaadin](https://www.baeldung.com/spring-boot-vaadin) diff --git a/vavr/README.md b/vavr/README.md index 6832f78a62..2b8bb25356 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -1,3 +1,7 @@ +## Vavr + +This module contains articles about Vavr. + ### Relevant Articles: - [Introduction to Vavr](https://www.baeldung.com/vavr) - [Guide to Try in Vavr](https://www.baeldung.com/vavr-try) diff --git a/xml/README.md b/xml/README.md index d1aa3a798b..367a0334f6 100644 --- a/xml/README.md +++ b/xml/README.md @@ -6,7 +6,9 @@ This module contains articles about eXtensible Markup Language (XML) - [Intro to XPath with Java](https://www.baeldung.com/java-xpath) - [Introduction to JiBX](https://www.baeldung.com/jibx) - [XML Libraries Support in Java](https://www.baeldung.com/java-xml-libraries) -- [DOM parsing with Xerces](https://www.baeldung.com/java-xerces-dom-parsing) +- [Working with XML Files in Java Using DOM Parsing](https://www.baeldung.com/java-xerces-dom-parsing) - [Write an org.w3.dom.Document to a File](https://www.baeldung.com/java-write-xml-document-file) - [Modifying an XML Attribute in Java](https://www.baeldung.com/java-modify-xml-attribute) - [Convert XML to HTML in Java](https://www.baeldung.com/java-convert-xml-to-html) +- [Parsing an XML File Using StAX](https://www.baeldung.com/java-stax) +- [Parsing an XML File Using SAX Parser](https://www.baeldung.com/java-sax-parser)