diff --git a/.gitignore b/.gitignore index 90daf38dee..349efbcb67 100644 --- a/.gitignore +++ b/.gitignore @@ -84,4 +84,10 @@ software-security/sql-injection-samples/derby.log spring-soap/src/main/java/com/baeldung/springsoap/gen/ /report-*.json transaction.log -*-shell.log \ No newline at end of file +*-shell.log + +apache-cxf/cxf-aegis/baeldung.xml +apache-fop/src/test/resources/input.xml +apache-fop/src/test/resources/output_herold.pdf +apache-fop/src/test/resources/output_html2fo.pdf +apache-fop/src/test/resources/output_jtidy.pdf \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png index 7165a51782..12af62c131 100644 Binary files a/algorithms-miscellaneous-2/src/test/resources/graph.png and b/algorithms-miscellaneous-2/src/test/resources/graph.png differ diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index a1456c6b20..93426b3e0d 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -16,4 +16,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency) - [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search) - [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm) +- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) +- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search) - More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-4/README.md b/algorithms-miscellaneous-4/README.md index 6aad9a43e4..df2eafb733 100644 --- a/algorithms-miscellaneous-4/README.md +++ b/algorithms-miscellaneous-4/README.md @@ -1,7 +1,6 @@ ## Algorithms - Miscellaneous -This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and -[genetic algorithms](/../algorithms-genetic), have their own dedicated modules. +This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](https://github.com/eugenp/tutorials/blob/algorithms-sorting) and [genetic algorithms](https://github.com/eugenp/tutorials/blob/algorithms-genetic), have their own dedicated modules. ### Relevant articles: @@ -12,4 +11,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings) - [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters) - [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations) -- More articles: [[<-- prev]](/../algorithms-miscellaneous-3) [[next -->]](/../algorithms-miscellaneous-5) +- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5) diff --git a/algorithms-miscellaneous-5/README.md b/algorithms-miscellaneous-5/README.md index 7a8f2e0a36..598fbab8b5 100644 --- a/algorithms-miscellaneous-5/README.md +++ b/algorithms-miscellaneous-5/README.md @@ -8,4 +8,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings) - [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree) - [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers) +- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack) - More articles: [[<-- prev]](/../algorithms-miscellaneous-4) diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTree.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTree.java new file mode 100644 index 0000000000..84180473e2 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTree.java @@ -0,0 +1,33 @@ +package com.baeldung.algorithms.balancedbinarytree; + +public class BalancedBinaryTree { + + public static boolean isBalanced(Tree tree) { + return isBalancedRecursive(tree, -1).isBalanced; + } + + private static Result isBalancedRecursive(Tree tree, int depth) { + if (tree == null) { + return new Result(true, -1); + } + + Result leftSubtreeResult = isBalancedRecursive(tree.left(), depth + 1); + Result rightSubtreeResult = isBalancedRecursive(tree.right(), depth + 1); + + boolean isBalanced = Math.abs(leftSubtreeResult.height - rightSubtreeResult.height) <= 1; + boolean subtreesAreBalanced = leftSubtreeResult.isBalanced && rightSubtreeResult.isBalanced; + int height = Math.max(leftSubtreeResult.height, rightSubtreeResult.height) + 1; + + return new Result(isBalanced && subtreesAreBalanced, height); + } + + private static final class Result { + private final boolean isBalanced; + private final int height; + + private Result(boolean isBalanced, int height) { + this.isBalanced = isBalanced; + this.height = height; + } + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/Tree.java b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/Tree.java new file mode 100644 index 0000000000..8e091408c9 --- /dev/null +++ b/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/balancedbinarytree/Tree.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.balancedbinarytree; + +public class Tree { + private final int value; + private final Tree left; + private final Tree right; + + public Tree(int value, Tree left, Tree right) { + this.value = value; + this.left = left; + this.right = right; + } + + public int value() { + return value; + } + + public Tree left() { + return left; + } + + public Tree right() { + return right; + } + + @Override + public String toString() { + return String.format("[%s, %s, %s]", + value, + left == null ? "null" : left.toString(), + right == null ? "null" : right.toString() + ); + } +} diff --git a/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/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/balancedbinarytree/BalancedBinaryTreeUnitTest.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java new file mode 100644 index 0000000000..25f313f991 --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.balancedbinarytree; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider { + + @Test + public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() { + for (Tree tree : balancedTrees()) { + assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree)); + } + } + + @Test + public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() { + for (Tree tree : unbalancedTrees()) { + assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree)); + } + } + + private String toString(Tree tree) { + return tree != null ? tree.toString() : "null"; + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BinaryTreeDataProvider.java b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BinaryTreeDataProvider.java new file mode 100644 index 0000000000..3f4318afbc --- /dev/null +++ b/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BinaryTreeDataProvider.java @@ -0,0 +1,69 @@ +package com.baeldung.algorithms.balancedbinarytree; + +import java.util.Arrays; +import java.util.Collection; + +class BinaryTreeDataProvider { + + static Collection balancedTrees() { + return Arrays.asList( + null, + leaf(1), + tree(1, leaf(2), leaf(3)), + tree( + 1, + leaf(2), + tree(3, leaf(4), null) + ), + tree( + 1, + tree( + 2, + tree(3, leaf(4), null), + leaf(5) + ), + tree( + 6, + leaf(7), + tree(8, null, leaf(9)) + ) + ) + ); + } + + static Collection unbalancedTrees() { + return Arrays.asList( + tree( + 1, + tree(2, leaf(3), null), + null + ), + tree( + 1, + tree( + 2, + tree(3, leaf(4), leaf(5)), + null + ), + tree(6, leaf(7), null) + ), + tree( + 1, + tree(2, leaf(3), null), + tree( + 4, + tree(5, leaf(6), leaf(7)), + null + ) + ) + ); + } + + private static Tree leaf(int value) { + return new Tree(value, null, null); + } + + private static Tree tree(int value, Tree left, Tree right) { + return new Tree(value, left, right); + } +} diff --git a/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/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 3f27cfea49..15a5ec6e02 100644 --- a/algorithms-sorting/README.md +++ b/algorithms-sorting/README.md @@ -17,3 +17,4 @@ This module contains articles about sorting algorithms. - [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) - [Radix Sort in Java](https://www.baeldung.com/java-radix-sort) - [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort) diff --git a/apache-fop/src/test/resources/input.xml b/apache-fop/src/test/resources/input.xml deleted file mode 100644 index a8266f3f5c..0000000000 --- a/apache-fop/src/test/resources/input.xml +++ /dev/null @@ -1,1674 +0,0 @@ - -
- - Bootstrap a Web Application with Spring 4 - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. The Maven pom.xml - - - 3. The Java based Web Configuration - - - 4. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. The Maven pom.xml - - -     2.1. Justification of the cglib dependency - - -     2.2. The cglib dependency in Spring 3.2 and beyond - - - 3. The Java based web configuration - - -    3.1. The web.xml - - - 4. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - The tutorial illustrates how to Bootstrap a Web Application with Spring and also discusses how to make the jump from XML to Java without having to completely migrate the entire XML configuration. -
-
- <anchor xml:id="dbdoclet.2_The_Maven_pomxml"/><emphasis role="bold">2. The Maven pom.xml</emphasis> - <project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation=" - http://maven.apache.org/POM/4.0.0 - http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>org</groupId> - <artifactId>rest</artifactId> - <version>0.0.1-SNAPSHOT</version> - <packaging>war</packaging> - - <dependencies> - - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring-webmvc</artifactId> - <version>${spring.version}</version> - <exclusions> - <exclusion> - <artifactId>commons-logging</artifactId> - <groupId>commons-logging</groupId> - </exclusion> - </exclusions> - </dependency> - - </dependencies> - - <build> - <finalName>rest</finalName> - - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <version>3.1</version> - <configuration> - <source>1.6</source> - <target>1.6</target> - <encoding>UTF-8</encoding> - </configuration> - </plugin> - </plugins> - </build> - - <properties> - <spring.version>4.0.5.RELEASE</spring.version> - </properties> - -</project> -
- <emphasis role="bold">2.1. The cglib dependency before Spring 3.2</emphasis> - You may wonder why cglib is a dependency – it turns out there is a valid reason to include it – the entire configuration cannot function without it. If removed, Spring will throw: - Caused by: java.lang.IllegalStateException: CGLIB is required to process @Configuration classes. Either add CGLIB to the classpath or remove the following @Configuration bean definitions - The reason this happens is explained by the way Spring deals with @Configuration classes. These classes are effectively beans, and because of this they need to be aware of the Context, and respect scope and other bean semantics. This is achieved by dynamically creating a cglib proxy with this awareness for each @Configuration class, hence the cglib dependency. - Also, because of this, there are a few restrictions for Configuration annotated classes: - - - Configuration classes should not be final - - - They should have a constructor with no arguments - - -
-
- <emphasis role="bold">2.2. The cglib dependency in Spring 3.2 and beyond</emphasis> - Starting with Spring 3.2, it is no longer necessary to add cglib as an explicit dependency. This is because Spring is in now inlining cglib – which will ensure that all class based proxying functionality will work out of the box with Spring 3.2. - The new cglib code is placed under the Spring package: org.springframework.cglib (replacing the original net.sf.cglib). The reason for the package change is to avoid conflicts with any cglib versions already existing on the classpath. - Also, the new cglib 3.0 is now used, upgraded from the older 2.2 dependency (see this JIRA issue for more details). - Finally, now that Spring 4.0 is out in the wild, changes like this one (removing the cglib dependency) are to be expected with Java 8 just around the corner – you can watch this Spring Jira to keep track of the Spring support, and the Java 8 Resources page to keep tabs on the that. -
-
-
- <anchor xml:id="dbdoclet.3_The_Java_based_Web_Configuration"/><emphasis role="bold">3. The Java based Web Configuration</emphasis> - @Configuration -@ImportResource( { "classpath*:/rest_config.xml" } ) -@ComponentScan( basePackages = "org.rest" ) -@PropertySource({ "classpath:rest.properties", "classpath:web.properties" }) -public class AppConfig{ - - @Bean -   public static PropertySourcesPlaceholderConfigurer properties() { -   return new PropertySourcesPlaceholderConfigurer(); -   } -} - First, the @Configuration annotation – this is the main artifact used by the Java based Spring configuration; it is itself meta-annotated with @Component, which makes the annotated classes standard beans and as such, also candidates for component scanning. The main purpose of @Configuration classes is to be sources of bean definitions for the Spring IoC Container. For a more detailed description, see the official docs. - Then, @ImportResource is used to import the existing XML based Spring configuration. This may be configuration which is still being migrated from XML to Java, or simply legacy configuration that you wish to keep. Either way, importing it into the Container is essential for a successful migration, allowing small steps without to much risk. The equivalent XML annotation that is replaced is: - <import resource=”classpath*:/rest_config.xml” /> - Moving on to @ComponentScan – this configures the component scanning directive, effectively replacing the XML: - <context:component-scan base-package="org.rest" /> - As of Spring 3.1, the @Configuration are excluded from classpath scanning by default – see this JIRA issue. Before Spring 3.1 though, these classes should have been excluded explicitly: - excludeFilters = { @ComponentScan.Filter( Configuration.class ) } - The @Configuration classes should not be autodiscovered because they are already specified and used by the Container – allowing them to be rediscovered and introduced into the Spring context will result in the following error: - Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name ‘webConfig’ for bean class [org.rest.spring.AppConfig] conflicts with existing, non-compatible bean definition of same name and class [org.rest.spring.AppConfig] - And finally, using the @Bean annotation to configure the properties support – PropertySourcesPlaceholderConfigurer is initialized in a @Bean annotated method, indicating it will produce a Spring bean managed by the Container. This new configuration has replaced the following XML: - <context:property-placeholder -location="classpath:persistence.properties, classpath:web.properties" -ignore-unresolvable="true"/> - For a more in depth discussion on why it was necessary to manually register the PropertySourcesPlaceholderConfigurer bean, see the Properties with Spring Tutorial. -
- <emphasis role="bold">3.1. The web.xml</emphasis> - <?xml version="1.0" encoding="UTF-8"?> -<web-app xmlns=" - http://java.sun.com/xml/ns/javaee" -     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" -     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -    xsi:schemaLocation=" - http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" -    id="rest" version="3.0"> - - <context-param> - <param-name>contextClass</param-name> - <param-value> - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - </param-value> - </context-param> - <context-param> - <param-name>contextConfigLocation</param-name> - <param-value>org.rest.spring.root</param-value> - </context-param> - <listener> - <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> - </listener> - - <servlet> - <servlet-name>rest</servlet-name> - <servlet-class> - org.springframework.web.servlet.DispatcherServlet - </servlet-class> - <init-param> - <param-name>contextClass</param-name> - <param-value> - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - </param-value> - </init-param> - <init-param> - <param-name>contextConfigLocation</param-name> - <param-value>org.rest.spring.rest</param-value> - </init-param> - <load-on-startup>1</load-on-startup> - </servlet> - <servlet-mapping> - <servlet-name>rest</servlet-name> - <url-pattern>/api/*</url-pattern> - </servlet-mapping> - - <welcome-file-list> - <welcome-file /> - </welcome-file-list> - -</web-app> - First, the root context is defined and configured to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext. The newer AnnotationConfigWebApplicationContext accepts @Configuration annotated classes as input for the Container configuration and is needed in order to set up the Java based context. Unlike XmlWebApplicationContext, it assumes no default configuration class locations, so the “contextConfigLocation”init-param for the Servlet must be set. This will point to the java package where the @Configuration classes are located; the fully qualified name(s) of the classes are also supported. - Next, the DispatcherServlet is configured to use the same kind of context, with the only difference that it’s loading configuration classes out of a different package. - Other than this, the web.xml doesn’t really change from a XML to a Java based configuration. -
-
-
- <anchor xml:id="dbdoclet.4_Conclusion"/><emphasis role="bold">4. Conclusion</emphasis> - The presented approach allows for a smooth migration of the Spring configuration from XML to Java, mixing the old and the new. This is important for older projects, which may have a lot of XML based configuration that cannot be migrated all at once. - This way, in a migration, the XML beans can be ported in small increments. - In the next article on REST with Spring, I cover setting up MVC in the project, configuration of the HTTP status codes, payload marshalling and content negotiation. - The implementation of this Bootstrap a Spring Web App Tutorial can be downloaded as a working sample project. - This is an Eclipse based project, so it should be easy to import and run as it is. - -   - - - - - - - - - java, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
- -
- - Build a REST API with Spring 4 and Java Config - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. Understanding REST in Spring - - - 3. The Java configuration - - - 4. Testing the Spring context - - - 5. The Controller - - - 6. Mapping the HTTP response codes - - - 7. Additional Maven dependencies - - - 8. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - -   - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. Understanding REST in Spring - - - 3. The Java configuration - - - 4. Testing the Spring context - - - 5. The Controller - - - 6. Mapping the HTTP response codes - - -     6.1. Unmapped requests - - -     6.2. Valid, mapped requests - - -     6.3. Client error - - -     6.4. Using @ExceptionHandler - - - 7. Additional Maven dependencies - - - 8. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This article shows how to set up REST in Spring – the Controller and HTTP response codes, configuration of payload marshalling and content negotiation. -
-
- <anchor xml:id="dbdoclet.2_Understanding_REST_in_Spring"/><emphasis role="bold">2. Understanding REST in Spring</emphasis> - The Spring framework supports 2 ways of creating RESTful services: - - - using MVC with ModelAndView - - - using HTTP message converters - - - The ModelAndView approach is older and much better documented, but also more verbose and configuration heavy. It tries to shoehorn the REST paradigm into the old model, which is not without problems. The Spring team understood this and provided first-class REST support starting with Spring 3.0. - The new approach, based on HttpMessageConverterand annotations, is much more lightweight and easy to implement. Configuration is minimal and it provides sensible defaults for what you would expect from a RESTful service. It is however newer and a a bit on the light side concerning documentation; what’s , the reference doesn’t go out of it’s way to make the distinction and the tradeoffs between the two approaches as clear as they should be. Nevertheless, this is the way RESTful services should be build after Spring 3.0. -
-
- <anchor xml:id="dbdoclet.3_The_Java_configuration"/><emphasis role="bold">3. The Java configuration</emphasis> - - @Configuration -@EnableWebMvc -public class WebConfig{ - // -} - The new @EnableWebMvc annotation does a number of useful things – specifically, in the case of REST, it detect the existence of Jackson and JAXB 2 on the classpath and automatically creates and registers default JSON and XML converters. The functionality of the annotation is equivalent to the XML version: - <mvc:annotation-driven /> - This is a shortcut, and though it may be useful in many situations, it’s not perfect. When more complex configuration is needed, remove the annotation and extend WebMvcConfigurationSupport directly. -
-
- <anchor xml:id="dbdoclet.4_Testing_the_Spring_context"/><emphasis role="bold">4. Testing the Spring context</emphasis> - Starting with Spring 3.1, we get first-class testing support for @Configuration classes: - @RunWith( SpringJUnit4ClassRunner.class ) -@ContextConfiguration( classes = { ApplicationConfig.class, PersistenceConfig.class }, - loader = AnnotationConfigContextLoader.class ) -public class SpringTest{ - - @Test - public void whenSpringContextIsInstantiated_thenNoExceptions(){ - // When - } -} - The Java configuration classes are simply specified with the @ContextConfiguration annotation and the new AnnotationConfigContextLoader loads the bean definitions from the @Configuration classes. - Notice that the WebConfig configuration class was not included in the test because it needs to run in a Servlet context, which is not provided. -
-
- <anchor xml:id="dbdoclet.5_The_Controller"/><emphasis role="bold">5. The Controller</emphasis> - The @Controller is the central artifact in the entire Web Tier of the RESTful API. For the purpose of this post, the controller is modeling a simple REST resource – Foo: - @Controller -@RequestMapping( value = "/foos" ) -class FooController{ - - @Autowired - IFooService service; - - @RequestMapping( method = RequestMethod.GET ) - @ResponseBody - public List< Foo > findAll(){ - return service.findAll(); - } - - @RequestMapping( value = "/{id}", method = RequestMethod.GET ) - @ResponseBody - public Foo findOne( @PathVariable( "id" ) Long id ){ - return RestPreconditions.checkFound( service.findOne( id ) ); - } - - @RequestMapping( method = RequestMethod.POST ) - @ResponseStatus( HttpStatus.CREATED ) - @ResponseBody - public Long create( @RequestBody Foo resource ){ - Preconditions.checkNotNull( resource ); - return service.create( resource ); - } - - @RequestMapping( value = "/{id}", method = RequestMethod.PUT ) - @ResponseStatus( HttpStatus.OK ) - public void update( @PathVariable( "id" ) Long id, @RequestBody Foo resource ){ - Preconditions.checkNotNull( resource ); - RestPreconditions.checkNotNull( service.getById( resource.getId() ) ); - service.update( resource ); - } - - @RequestMapping( value = "/{id}", method = RequestMethod.DELETE ) - @ResponseStatus( HttpStatus.OK ) - public void delete( @PathVariable( "id" ) Long id ){ - service.deleteById( id ); - } - -} - You may have noticed I’m using a very simple, guava style RestPreconditions utility: - public class RestPreconditions { - public static <T> T checkFound(final T resource) { - if (resource == null) { - throw new MyResourceNotFoundException(); - } - return resource; - } -} - The Controller implementation is non-public – this is because it doesn’t need to be. Usually the controller is the last in the chain of dependencies – it receives HTTP requests from the Spring front controller (the DispathcerServlet) and simply delegate them forward to a service layer. If there is no use case where the controller has to be injected or manipulated through a direct reference, then I prefer not to declare it as public. - The request mappings are straightforward – as with any controller, the actual value of the mapping as well as the HTTP method are used to determine the target method for the request. @RequestBody will bind the parameters of the method to the body of the HTTP request, whereas @ResponseBody does the same for the response and return type. They also ensure that the resource will be marshalled and unmarshalled using the correct HTTP converter. Content negotiation will take place to choose which one of the active converters will be used, based mostly on the Accept header, although other HTTP headers may be used to determine the representation as well. -
-
- <anchor xml:id="dbdoclet.6_Mapping_the_HTTP_response_codes"/><emphasis role="bold">6. Mapping the HTTP response codes</emphasis> - The status codes of the HTTP response are one of the most important parts of the REST service, and the subject can quickly become very complex. Getting these right can be what makes or breaks the service. -
- <emphasis role="bold">6.1. Unmapped requests</emphasis> - If Spring MVC receives a request which doesn’t have a mapping, it considers the request not to be allowed and returns a 405 METHOD NOT ALLOWED back to the client. It is also good practice to include the Allow HTTP header when returning a 405 to the client, in order to specify which operations are allowed. This is the standard behavior of Spring MVC and does not require any additional configuration. -
-
- <emphasis role="bold">6.2. Valid, mapped requests</emphasis> - For any request that does have a mapping, Spring MVC considers the request valid and responds with 200 OK if no other status code is specified otherwise. It is because of this that controller declares different @ResponseStatus for the create, update and delete actions but not for get, which should indeed return the default 200 OK. -
-
- <emphasis role="bold">6.3. Client error</emphasis> - In case of a client error, custom exceptions are defined and mapped to the appropriate error codes. Simply throwing these exceptions from any of the layers of the web tier will ensure Spring maps the corresponding status code on the HTTP response. - @ResponseStatus( value = HttpStatus.BAD_REQUEST ) -public class BadRequestException extends RuntimeException{ - // -} -@ResponseStatus( value = HttpStatus.NOT_FOUND ) -public class ResourceNotFoundException extends RuntimeException{ - // -} - These exceptions are part of the REST API and, as such, should only be used in the appropriate layers corresponding to REST; if for instance a DAO/DAL layer exist, it should not use the exceptions directly. Note also that these are not checked exceptions but runtime exceptions – in line with Spring practices and idioms. -
-
- <emphasis role="bold">6.4. Using @ExceptionHandler</emphasis> - Another option to map custom exceptions on specific status codes is to use the @ExceptionHandler annotation in the controller. The problem with that approach is that the annotation only applies to the controller in which it is defined, not to the entire Spring Container, which means that it needs to be declared in each controller individually. This quickly becomes cumbersome, especially in more complex applications which many controllers. There are a few JIRA issues opened with Spring at this time to handle this and other related limitations: SPR-8124, SPR-7278, SPR-8406. -
-
-
- <anchor xml:id="dbdoclet.7_Additional_Maven_dependencies"/><emphasis role="bold">7. Additional Maven dependencies</emphasis><emphasis role="bold"></emphasis> - In addition to the spring-webmvc dependency required for the standard web application, we’ll need to set up content marshalling and unmarshalling for the REST API: - <dependencies> - <dependency> -   <groupId>com.fasterxml.jackson.core</groupId> -    <artifactId>jackson-databind</artifactId> -   <version>${jackson.version}</version> - </dependency> - <dependency> - <groupId>javax.xml.bind</groupId> - <artifactId>jaxb-api</artifactId> - <version>${jaxb-api.version}</version> - <scope>runtime</scope> - </dependency> -</dependencies> - -<properties> - <jackson.version>2.4.0</jackson.version> - <jaxb-api.version>2.2.11</jaxb-api.version> -</properties> - These are the libraries used to convert the representation of the REST resource to either JSON or XML. -
-
- <anchor xml:id="dbdoclet.8_Conclusion"/><emphasis role="bold">8. Conclusion</emphasis> - This tutorial illustrated how to implement and configure a REST Service using Spring 4 and Java based configuration, discussing HTTP response codes, basic Content Negotiation and marshaling. - In the next articles of the series I will focus on Discoverability of the API, advanced content negotiation and working with additional representations of a Resource. - The implementation of this Spring REST API Tutorial can be downloaded as a working sample project. - This is an Eclipse based project, so it should be easy to import and run as it is. - - - - - - - - - - java, REST, Spring, testing - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - - - -
-
-
- -
- - Spring Security for a REST API - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. Spring Security in the web.xml - - - 3. The Security Configuration - - - 4. Maven and other trouble - - - 5. Conclusion - - - - - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. Introducing Spring Security in the web.xml - - - 3. The Security Configuration - - -     3.1. The basics - - -     3.2. The Entry Point - - -     3.3. The Login - - -     3.4. Authentication should return 200 instead of 301 - - -     3.5. Failed Authentication should return 401 instead of 302 - - -     3.6. The Authentication Manager and Provider - - -     3.7. Finally – Authentication against the running REST Service - - - 4. Maven and other trouble - - - 5. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This tutorial shows how to Secure a REST Service using Spring and Spring Security 3.1 with Java based configuration. The article will focus on how to set up the Security Configuration specifically for the REST API using a Login and Cookie approach. -
-
- <anchor xml:id="dbdoclet.2_Spring_Security_in_the_webxml"/><emphasis role="bold">2. Spring Security in the web.xml</emphasis> - The architecture of Spring Security is based entirely on Servlet Filters and, as such, comes before Spring MVC in regards to the processing of HTTP requests. Keeping this in mind, to begin with, a filter needs to be declared in the web.xml of the application: - <filter> - <filter-name>springSecurityFilterChain</filter-name> - <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> -</filter> -<filter-mapping> - <filter-name>springSecurityFilterChain</filter-name> - <url-pattern>/*</url-pattern> -</filter-mapping> - The filter must necessarily be named ‘springSecurityFilterChain’  to match the default bean created by Spring Security in the container. - Note that the defined filter is not the actual class implementing the security logic but a DelegatingFilterProxy with the purpose of delegating the Filter’s methods to an internal bean. This is done so that the target bean can still benefit from the Spring context lifecycle and flexibility. - The URL pattern used to configure the Filter is /* even though the entire web service is mapped to /api/* so that the security configuration has the option to secure other possible mappings as well, if required. -
-
- <anchor xml:id="dbdoclet.3_The_Security_Configuration"/><emphasis role="bold">3. The Security Configuration</emphasis> - <?xml version="1.0" encoding="UTF-8"?> -<beans:beans - xmlns="http://www.springframework.org/schema/security" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:beans="http://www.springframework.org/schema/beans" - xmlns:sec="http://www.springframework.org/schema/security" - xsi:schemaLocation=" - http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-3.2.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> - - <http entry-point-ref="restAuthenticationEntryPoint"> - <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN"/> - - <form-login - authentication-success-handler-ref="mySuccessHandler" - authentication-failure-handler-ref="myFailureHandler" - /> - - <logout /> - </http> - - <beans:bean id="mySuccessHandler" - class="org.rest.security.MySavedRequestAwareAuthenticationSuccessHandler"/> - <beans:bean id="myFailureHandler" - class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/> - - <authentication-manager alias="authenticationManager"> - <authentication-provider> - <user-service> - <user name="temporary" password="temporary" authorities="ROLE_ADMIN"/> - <user name="user" password="user" authorities="ROLE_USER"/> - </user-service> - </authentication-provider> - </authentication-manager> - -</beans:beans> - Most of the configuration is done using the security namespace – for this to be enabled, the schema locations must be defined and pointed to the correct 3.1 or 3.2 XSD versions. The namespace is designed so that it expresses the common uses of Spring Security while still providing hooks raw beans to accommodate more advanced scenarios. >> Signup for my upcoming Video Course on Building a REST API with Spring 4 -
- <emphasis role="bold">3.1. The <http> element</emphasis> - The <http> element is the main container element for HTTP security configuration. In the current implementation, it only secured a single mapping: /api/admin/**. Note that the mapping is relative to the root context of the web application, not to the rest Servlet; this is because the entire security configuration lives in the root Spring context and not in the child context of the Servlet. -
-
- <emphasis role="bold">3.2. The Entry Point</emphasis> - In a standard web application, the authentication process may be automatically triggered when the client tries to access a secured resource without being authenticated – this is usually done by redirecting to a login page so that the user can enter credentials. However, for a REST Web Service this behavior doesn’t make much sense – Authentication should only be done by a request to the correct URI and all other requests should simply fail with a 401 UNAUTHORIZED status code if the user is not authenticated. - Spring Security handles this automatic triggering of the authentication process with the concept of an Entry Point – this is a required part of the configuration, and can be injected via the entry-point-ref attribute of the <http> element. Keeping in mind that this functionality doesn’t make sense in the context of the REST Service, the new custom entry point is defined to simply return 401 whenever it is triggered: - @Component( "restAuthenticationEntryPoint" ) -public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{ - - @Override - public void commence( HttpServletRequest request, HttpServletResponse response, - AuthenticationException authException ) throws IOException{ - response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); - } -} - A quick sidenote here is that the 401 is sent without the WWW-Authenticate header, as required by the HTTP Spec – we can of course set the value manually if we need to. -
-
- <emphasis role="bold">3.3. The Login Form for REST</emphasis> - There are multiple ways to do Authentication for a REST API – one of the default Spring Security provides is Form Login – which uses an authentication processing filter – org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter. - The <form-login> element will create this filter and will also allow us to set our custom authentication success handler on it. This can also be done manually by using the <custom-filter> element to register a filter at the position FORM_LOGIN_FILTER – but the namespace support is flexible enough. - Note that for a standard web application, the auto-config attribute of the <http> element is shorthand syntax for some useful security configuration. While this may be appropriate for some very simple configurations, it doesn’t fit and should not be used for a REST API. -
-
- <emphasis role="bold">3.4. Authentication should return 200 instead of 301</emphasis> - By default, form login will answer a successful authentication request with a 301 MOVED PERMANENTLY status code; this makes sense in the context of an actual login form which needs to redirect after login. For a RESTful web service however, the desired response for a successful authentication should be 200 OK. - This is done by injecting a custom authentication success handler in the form login filter, to replace the default one. The new handler implements the exact same login as the default org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler with one notable difference – the redirect logic is removed: - public class MySavedRequestAwareAuthenticationSuccessHandler - extends SimpleUrlAuthenticationSuccessHandler { - - private RequestCache requestCache = new HttpSessionRequestCache(); - - @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, - Authentication authentication) throws ServletException, IOException { - SavedRequest savedRequest = requestCache.getRequest(request, response); - - if (savedRequest == null) { - clearAuthenticationAttributes(request); - return; - } - String targetUrlParam = getTargetUrlParameter(); - if (isAlwaysUseDefaultTargetUrl() || - (targetUrlParam != null && - StringUtils.hasText(request.getParameter(targetUrlParam)))) { - requestCache.removeRequest(request, response); - clearAuthenticationAttributes(request); - return; - } - - clearAuthenticationAttributes(request); - } - - public void setRequestCache(RequestCache requestCache) { - this.requestCache = requestCache; - } -} -
-
- <emphasis role="bold">3.5. Failed Authentication should return 401 instead of 302</emphasis> - Similarly – we configured the authentication failure handler – same way we did with the success handler. - Luckily – in this case, we don’t need to actually define a new class for this handler – the standard implementation – SimpleUrlAuthenticationFailureHandler – does just fine. - The only difference is that – now that we’re defining this explicitly in our XML config – it’s not going to get a default defaultFailureUrl from Spring – and so it won’t redirect. -
-
- <emphasis role="bold">3.6. The Authentication Manager and Provider</emphasis> - The authentication process uses an in-memory provider to perform authentication – this is meant to simplify the configuration as a production implementation of these artifacts is outside the scope of this post. -
-
- <emphasis role="bold">3.7 Finally – Authentication against the running REST Service</emphasis> - Now let’s see how we can authenticate against the REST API – the URL for login is /j_spring_security_check – and a simple curl command performing login would be: - curl -i -X POST -d j_username=user -d j_password=userPass -http://localhost:8080/spring-security-rest/j_spring_security_check - This request will return the Cookie which will then be used by any subsequent request against the REST Service. - We can use curl to authentication and store the cookie it receives in a file: - curl -i -X POST -d j_username=user -d j_password=userPass -c /opt/cookies.txt -http://localhost:8080/spring-security-rest/j_spring_security_check - Then we can use the cookie from the file to do further authenticated requests: - curl -i --header "Accept:application/json" -X GET -b /opt/cookies.txt -http://localhost:8080/spring-security-rest/api/foos - This authenticated request will correctly result in a 200 OK: - HTTP/1.1 200 OK -Server: Apache-Coyote/1.1 -Content-Type: application/json;charset=UTF-8 -Transfer-Encoding: chunked -Date: Wed, 24 Jul 2013 20:31:13 GMT - -[{"id":0,"name":"JbidXc"}] -
-
-
- <anchor xml:id="dbdoclet.4_Maven_and_other_trouble"/><emphasis role="bold">4. Maven and other trouble</emphasis> - The Spring core dependencies necessary for a web application and for the REST Service have been discussed in detail. For security, we’ll need to add: spring-security-web and spring-security-config – all of these have also been covered in the Maven for Spring Security tutorial. - It’s worth paying close attention to the way Maven will resolve the older Spring dependencies – the resolution strategy will start causing problems once the security artifacts are added to the pom. To address this problem, some of the core dependencies will need to be overridden in order to keep them at the right version. -
-
- <anchor xml:id="dbdoclet.5_Conclusion"/><emphasis role="bold">5. Conclusion</emphasis> - This post covered the basic security configuration and implementation for a RESTful Service using Spring Security 3.1, discussing the web.xml, the security configuration, the HTTP status codes for the authentication process and the Maven resolution of the security artifacts. - The implementation of this Spring Security REST Tutorial can be downloaded as a working sample project.This is an Eclipse based project, so it should be easy to import and run as it is. - - - - - - - - - - REST, security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - - - -
-
-
- -
- - Spring Security Basic Authentication - - - - - - Return to Content - - - - - - Contents - - - 1. Overview - - - 2. The Spring Security Configuration - - - 3. Consuming The Secured Application - - - 4. Further Configuration – The Entry Point - - - 5. The Maven Dependencies - - - 6. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This tutorial shows how to set up, configure and customize Basic Authentication with Spring. We’re going to built on top of the simple Spring MVC example, and secure the UI of the MVC application with the Basic Auth mechanism provided by Spring Security. -
- <anchor xml:id="dbdoclet.2_The_Spring_Security_Configuration"/><emphasis role="bold">2. The Spring Security Configuration</emphasis> - The Configuration for Spring Security is still XML: - <?xml version="1.0" encoding="UTF-8"?> -<beans:beans xmlns="http://www.springframework.org/schema/security" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:beans="http://www.springframework.org/schema/beans" - xsi:schemaLocation=" - http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-3.1.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> - - <http use-expressions="true"> - <intercept-url pattern="/**" access="isAuthenticated()" /> - - <http-basic /> - </http> - - <authentication-manager> - <authentication-provider> - <user-service> - <user name="user1" password="user1Pass" authorities="ROLE_USER" /> - </user-service> - </authentication-provider> - </authentication-manager> - -</beans:beans> - This is one of the last pieces of configuration in Spring that still need XML – Java Configuration for Spring Security is still a work in progress. - What is relevant here is the <http-basic> element inside the main <http> element of the configuration – this is enough to enable Basic Authentication for the entire application. The Authentication Manager is not the focus of this tutorial, so we are using an in memory manager with the user and password defined in plaintext. - The web.xml of the web application enabling Spring Security has already been discussed in the Spring Logout tutorial. -
-
- <anchor xml:id="dbdoclet.3_Consuming_The_Secured_Application"/><emphasis role="bold">3. Consuming The Secured Application</emphasis> - The curl command is our go to tool for consuming the secured application. - First, let’s try to request the /homepage.html without providing any security credentials: - curl -i http://localhost:8080/spring-security-mvc-basic-auth/homepage.html - We get back the expected 401 Unauthorized and the Authentication Challenge: - HTTP/1.1 401 Unauthorized -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=E5A8D3C16B65A0A007CFAACAEEE6916B; Path=/spring-security-mvc-basic-auth/; HttpOnly -WWW-Authenticate: Basic realm="Spring Security Application" -Content-Type: text/html;charset=utf-8 -Content-Length: 1061 -Date: Wed, 29 May 2013 15:14:08 GMT - The browser would interpret this challenge and prompt us for credentials with a simple dialog, but since we’re using curl, this isn’t the case. - Now, let’s request the same resource – the homepage – but provide the credentials to access it as well: - curl -i --user user1:user1Pass http://localhost:8080/spring-security-mvc-basic-auth/homepage.html - Now, the response from the server is 200 OK along with a Cookie: - HTTP/1.1 200 OK -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=301225C7AE7C74B0892887389996785D; Path=/spring-security-mvc-basic-auth/; HttpOnly -Content-Type: text/html;charset=ISO-8859-1 -Content-Language: en-US -Content-Length: 90 -Date: Wed, 29 May 2013 15:19:38 GMT - From the browser, the application can be consumed normally – the only difference is that a login page is no longer a hard requirement since all browsers support Basic Authentication and use a dialog to prompt the user for credentials. -
-
- <anchor xml:id="dbdoclet.4_Further_Configuration_8211_The_Entry_Point"/><emphasis role="bold">4. Further Configuration – </emphasis><emphasis role="bold">The Entry Point</emphasis> - By default, the BasicAuthenticationEntryPoint provisioned by Spring Security returns a full html page for a 401 Unauthorized response back to the client. This html representation of the error renders well in a browser, but it not well suited for other scenarios, such as a REST API where a json representation may be preferred. - The namespace is flexible enough for this new requirement as well – to address this – the entry point can be overridden: - <http-basic entry-point-ref="myBasicAuthenticationEntryPoint" /> - The new entry point is defined as a standard bean: - @Component -public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { - - @Override - public void commence - (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) - throws IOException, ServletException { - response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - PrintWriter writer = response.getWriter(); - writer.println("HTTP Status 401 - " + authEx.getMessage()); - } - - @Override - public void afterPropertiesSet() throws Exception { - setRealmName("Baeldung"); - super.afterPropertiesSet(); - } -} - By writing directly to the HTTP Response we now have full control over the format of the response body. -
-
- <anchor xml:id="dbdoclet.5_The_Maven_Dependencies"/><emphasis role="bold">5. The Maven Dependencies</emphasis> - The Maven dependencies for Spring Security have been discussed before in the Spring Security with Maven article – we will need both spring-security-web and spring-security-config available at runtime. -
-
- <anchor xml:id="dbdoclet.6_Conclusion"/><emphasis role="bold">6. Conclusion</emphasis> - In this example we secured an MVC application with Spring Security and Basic Authentication. We discussed the XML configuration and we consumed the application with simple curl commands. Finally took control of the exact error message format – moving from the standard HTML error page to a custom text or json format. - The implementation of this Spring tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is. When the project runs locally, the sample html can be accessed at: - http://localhost:8080/spring-security-mvc-basic-auth/homepage.html - - - - - - - - - - security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
- -
- - Spring Security Digest Authentication - - - - - - Return to Content - - - - - - Contents - - - 1. Overview - - - 2. The Security XML Configuration - - - 3. Consuming the Secured Application - - - 4. The Maven Dependencies - - - 5. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This tutorial shows how to set up, configure and customize Digest Authentication with Spring. Similar to the previous article covering Basic Authentication, we’re going to built on top of the Spring MVC tutorial, and secure the application with the Digest Auth mechanism provided by Spring Security. -
- <anchor xml:id="dbdoclet.2_The_Security_XML_Configuration"/><emphasis role="bold">2. The Security XML Configuration</emphasis> - First thing to understand about the configuration is that, while Spring Security does have full out of the box support for the Digest authentication mechanism, this support is not as well integrated into the namespace as Basic Authentication was. - In this case, we need to manually define the raw beans that are going to make up the security configuration – the DigestAuthenticationFilter and the DigestAuthenticationEntryPoint: - <?xml version="1.0" encoding="UTF-8"?> -<beans:beans xmlns="http://www.springframework.org/schema/security" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:beans="http://www.springframework.org/schema/beans" - xsi:schemaLocation=" - http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-3.1.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> - -    <beans:bean id="digestFilter" - class="org.springframework.security.web.authentication.www.DigestAuthenticationFilter"> -        <beans:property name="userDetailsService" ref="userService" /> -        <beans:property name="authenticationEntryPoint" ref="digestEntryPoint" /> -    </beans:bean> -    <beans:bean id="digestEntryPoint"  - class="org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint"> -        <beans:property name="realmName" value="Contacts Realm via Digest Authentication" /> -        <beans:property name="key" value="acegi" /> -    </beans:bean> - - <!-- the security namespace configuration --> - <http use-expressions="true" entry-point-ref="digestEntryPoint"> - <intercept-url pattern="/**" access="isAuthenticated()" /> - - <custom-filter ref="digestFilter" after="BASIC_AUTH_FILTER" /> - </http> - - <authentication-manager> - <authentication-provider> - <user-service id="userService"> - <user name="user1" password="user1Pass" authorities="ROLE_USER" /> - </user-service> - </authentication-provider> - </authentication-manager> - -</beans:beans> - Next, we need to integrate these beans into the overall security configuration – and in this case, the namespace is still flexible enough to allow us to do that. - The first part of this is pointing to the custom entry point bean, via the entry-point-ref attribute of the main <http> element. - The second part is adding the newly defined digest filter into the security filter chain. Since this filter is functionally equivalent to the BasicAuthenticationFilter, we are using the same relative position in the chain – this is specified by the BASIC_AUTH_FILTER alias in the overall Spring Security Standard Filters. - Finally, notice that the Digest Filter is configured to point to the user service bean – and here, the namespace is again very useful as it allows us to specify a bean name for the default user service created by the <user-service> element: - <user-service id="userService"> -
-
- <anchor xml:id="dbdoclet.3_Consuming_the_Secured_Application"/><emphasis role="bold">3. Consuming the Secured Application</emphasis> - We’re going to be using the curl command to consume the secured application and understand how a client can interact with it. - Let’s start by requesting the homepage – without providing security credentials in the request: - curl -i http://localhost/spring-security-mvc-digest-auth/homepage.html - As expected, we get back a response with a 401 Unauthorized status code: - HTTP/1.1 401 Unauthorized -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=CF0233C...; Path=/spring-security-mvc-digest-auth/; HttpOnly -WWW-Authenticate: Digest realm="Contacts Realm via Digest Authentication", qop="auth", - nonce="MTM3MzYzODE2NTg3OTo3MmYxN2JkOWYxZTc4MzdmMzBiN2Q0YmY0ZTU0N2RkZg==" -Content-Type: text/html;charset=utf-8 -Content-Length: 1061 -Date: Fri, 12 Jul 2013 14:04:25 GMT - If this request were sent by the browser, the authentication challenge would prompt the user for credentials using a simple user/password dialog. - Let’s now provide the correct credentials and send the request again: - curl -i --digest --user - user1:user1Pass http://localhost/spring-security-mvc-digest-auth/homepage.html - Notice that we are enabling Digest Authentication for the curl command via the –digest flag. - The first response from the server will be the same – the 401 Unauthorized – but the challenge will now be interpreted and acted upon by a second request – which will succeed with a 200 OK: - HTTP/1.1 401 Unauthorized -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=A961E0D...; Path=/spring-security-mvc-digest-auth/; HttpOnly -WWW-Authenticate: Digest realm="Contacts Realm via Digest Authentication", qop="auth", - nonce="MTM3MzYzODgyOTczMTo3YjM4OWQzMGU0YTgwZDg0YmYwZjRlZWJjMDQzZWZkOA==" -Content-Type: text/html;charset=utf-8 -Content-Length: 1061 -Date: Fri, 12 Jul 2013 14:15:29 GMT - -HTTP/1.1 200 OK -Server: Apache-Coyote/1.1 -Set-Cookie: JSESSIONID=55F996B...; Path=/spring-security-mvc-digest-auth/; HttpOnly -Content-Type: text/html;charset=ISO-8859-1 -Content-Language: en-US -Content-Length: 90 -Date: Fri, 12 Jul 2013 14:15:29 GMT - -<html> -<head></head> - -<body> - <h1>This is the homepage</h1> -</body> -</html> - A final note on this interaction is that a client can preemptively send the correct Authorization header with the first request, and thus entirely avoid the server security challenge and the second request. -
-
- <anchor xml:id="dbdoclet.4_The_Maven_Dependencies"/><emphasis role="bold">4. The Maven Dependencies</emphasis> - The security dependencies are discussed in depth in the Spring Security Maven tutorial. In short, we will need to define spring-security-web and spring-security-config as dependencies in our pom.xml. -
-
- <anchor xml:id="dbdoclet.5_Conclusion"/><emphasis role="bold">5. Conclusion</emphasis> - In this tutorial we introduce security into a simple Spring MVC project by leveraging the Digest Authentication support in the framework. - The implementation of these examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is. - When the project runs locally, the homepage html can be accessed at (or, with minimal Tomcat configuration, on port 80): - http://localhost:8080/spring-security-mvc-digest-auth/homepage.html - Finally, there is no reason an application needs to choose between Basic and Digest authentication – both can be set up simultaneously on the same URI structure, in such a way that the client can pick between the two mechanisms when consuming the web application. - - - - - - - - - - security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
- -
- - Basic and Digest Authentication for a REST Service with Spring Security - - - - - - Return to Content - - - - - - Contents - - - Table of Contents - - - 1. Overview - - - 2. Configuration of Basic Authentication - - - 3. Configuration of Digest Authentication - - - 4. Supporting both authentication protocols in the same RESTful service - - - 5. Testing both scenarios - - - 6. Conclusion - - - If you're new here, you may want to get my "REST APIs with Spring" eBook. Thanks for visiting! - - - -
- <anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis> - - - 1. Overview - - - 2. Configuration of Basic Authentication - - -     2.1. Satisfying the stateless constraint – getting rid of sessions - - - 3. Configuration of Digest Authentication - - - 4. Supporting both authentication protocols in the same RESTful service - - -     4.1. Anonymous request - - -     4.2. Request with authentication credentials - - - 5. Testing both scenarios - - - 6. Conclusion - - -
- <anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis> - This article discusses how to set up both Basic and Digest Authentication on the same URI structure of a REST API. In a previous article, we discussed another method of securing the REST Service – form based authentication, so Basic and Digest authentication is the natural alternative, as well as the more RESTful one. -
-
- <anchor xml:id="dbdoclet.2_Configuration_of_Basic_Authentication"/><emphasis role="bold">2. Configuration of Basic Authentication</emphasis> - The main reason that form based authentication is not ideal for a RESTful Service is that Spring Security will make use of Sessions – this is of course state on the server, so the statelessness constraints in REST is practically ignored. - We’ll start by setting up Basic Authentication – first we remove the old custom entry point and filter from the main <http> security element: - <http create-session="stateless"> - <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN" /> - - <http-basic /> -</http> - Note how support for basic authentication has been added with a single configuration line – <http-basic /> – which handles the creation and wiring of both the BasicAuthenticationFilter and the BasicAuthenticationEntryPoint. -
- <emphasis role="bold">2.1. Satisfying the stateless constraint – getting rid of sessions</emphasis> - One of the main constraints of the RESTful architectural style is that the client-server communication is fully stateless, as the original dissertation reads: -
-     5.1.3 Stateless - We next add a constraint to the client-server interaction: communication must be stateless in nature, as in the client-stateless-server (CSS) style of Section 3.4.3 (Figure 5-3), such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. -
- The concept of Session on the server is one with a long history in Spring Security, and removing it entirely has been difficult until now, especially when configuration was done by using the namespace. However, Spring Security 3.1 augments the namespace configuration with a new stateless option for session creation, which effectively guarantees that no session will be created or used by Spring. What this new option does is completely removes all session related filters from the security filter chain, ensuring that authentication is performed for each request. -
-
-
- <anchor xml:id="dbdoclet.3_Configuration_of_Digest_Authentication"/><emphasis role="bold">3. Configuration of Digest Authentication</emphasis> - Starting with the previous configuration, the filter and entry point necessary to set up digest authentication will be defined as beans. Then, the digest entry point will override the one created by <http-basic> behind the scenes. Finally, the custom digest filter will be introduced in the security filter chain using the after semantics of the security namespace to position it directly after the basic authentication filter. - <http create-session="stateless" entry-point-ref="digestEntryPoint"> - <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN" /> - - <http-basic /> - <custom-filter ref="digestFilter" after="BASIC_AUTH_FILTER" /> -</http> - -<beans:bean id="digestFilter" class= - "org.springframework.security.web.authentication.www.DigestAuthenticationFilter"> - <beans:property name="userDetailsService" ref="userService" /> - <beans:property name="authenticationEntryPoint" ref="digestEntryPoint" /> -</beans:bean> - -<beans:bean id="digestEntryPoint" class= - "org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint"> - <beans:property name="realmName" value="Contacts Realm via Digest Authentication"/> - <beans:property name="key" value="acegi" /> -</beans:bean> - -<authentication-manager> - <authentication-provider> - <user-service id="userService"> - <user name="eparaschiv" password="eparaschiv" authorities="ROLE_ADMIN" /> - <user name="user" password="user" authorities="ROLE_USER" /> - </user-service> - </authentication-provider> -</authentication-manager> - Unfortunately there is no support in the security namespace to automatically configure the digest authentication the way basic authentication can be configured with <http-basic>. Because of that, the necessary beans had to be defined and wired manually into the security configuration. -
-
- <anchor xml:id="dbdoclet.4_Supporting_both_authentication_protocols_in_the_same_RESTful_service"/><emphasis role="bold">4. Supporting both authentication protocols in the same RESTful service</emphasis> - Basic or Digest authentication alone can be easily implemented in Spring Security 3.x; it is supporting both of them for the same RESTful web service, on the same URI mappings that introduces a new level of complexity into the configuration and testing of the service. -
- <emphasis role="bold">4.1. Anonymous request</emphasis> - With both basic and digest filters in the security chain, the way a anonymous request – a request containing no authentication credentials (Authorization HTTP header) – is processed by Spring Security is – the two authentication filters will find no credentials and will continue execution of the filter chain. Then, seeing how the request wasn’t authenticated, an AccessDeniedException is thrown and caught in the ExceptionTranslationFilter, which commences the digest entry point, prompting the client for credentials. - The responsibilities of both the basic and digest filters are very narrow – they will continue to execute the security filter chain if they are unable to identify the type of authentication credentials in the request. It is because of this that Spring Security can have the flexibility to be configured with support for multiple authentication protocols on the same URI. - When a request is made containing the correct authentication credentials – either basic or digest – that protocol will be rightly used. However, for an anonymous request, the client will get prompted only for digest authentication credentials. This is because the digest entry point is configured as the main and single entry point of the Spring Security chain; as such digest authentication can be considered the default. -
-
- <emphasis role="bold">4.2. Request with authentication credentials</emphasis> - A request with credentials for Basic authentication will be identified by the Authorization header starting with the prefix “Basic”. When processing such a request, the credentials will be decoded in the basic authentication filter and the request will be authorized. Similarly, a request with credentials for Digest authentication will use the prefix “Digest”  for it’s Authorization header. -
-
-
- <anchor xml:id="dbdoclet.5_Testing_both_scenarios"/><emphasis role="bold">5. Testing both scenarios</emphasis> - The tests will consume the REST service by creating a new resource after authenticating with either basic or digest: - @Test -public void givenAuthenticatedByBasicAuth_whenAResourceIsCreated_then201IsReceived(){ - // Given - // When - Response response = given() - .auth().preemptive().basic( ADMIN_USERNAME, ADMIN_PASSWORD ) - .contentType( HttpConstants.MIME_JSON ).body( new Foo( randomAlphabetic( 6 ) ) ) - .post( paths.getFooURL() ); - - // Then - assertThat( response.getStatusCode(), is( 201 ) ); -} -@Test -public void givenAuthenticatedByDigestAuth_whenAResourceIsCreated_then201IsReceived(){ - // Given - // When - Response response = given() - .auth().digest( ADMIN_USERNAME, ADMIN_PASSWORD ) - .contentType( HttpConstants.MIME_JSON ).body( new Foo( randomAlphabetic( 6 ) ) ) - .post( paths.getFooURL() ); - - // Then - assertThat( response.getStatusCode(), is( 201 ) ); -} - Note that the test using basic authentication adds credentials to the request preemptively, regardless if the server has challenged for authentication or not. This is to ensure that the server doesn’t need to challenge the client for credentials, because if it did, the challenge would be for Digest credentials, since that is the default. -
-
- <anchor xml:id="dbdoclet.6_Conclusion"/><emphasis role="bold">6. Conclusion</emphasis> - This article covered the configuration and implementation of both Basic and Digest authentication for a RESTful service, using mostly Spring Security 3.0 namespace support as well as some new features added by Spring Security 3.1. - For the full implementation, check out the github project. - - - - - - - - - - REST, security, Spring - - - - - - - - - - - © 2014 Baeldung. All Rights Reserved. - - - - - - - -
-
-
diff --git a/apache-fop/src/test/resources/output_herold.pdf b/apache-fop/src/test/resources/output_herold.pdf deleted file mode 100644 index 1d23de7b61..0000000000 Binary files a/apache-fop/src/test/resources/output_herold.pdf and /dev/null differ diff --git a/apache-fop/src/test/resources/output_html2fo.pdf b/apache-fop/src/test/resources/output_html2fo.pdf deleted file mode 100644 index 7c2b4a0c51..0000000000 Binary files a/apache-fop/src/test/resources/output_html2fo.pdf and /dev/null differ diff --git a/apache-fop/src/test/resources/output_jtidy.pdf b/apache-fop/src/test/resources/output_jtidy.pdf deleted file mode 100644 index 1d9456122c..0000000000 Binary files a/apache-fop/src/test/resources/output_jtidy.pdf and /dev/null differ diff --git a/code-generation/pom.xml b/code-generation/pom.xml index b52e558b53..91ce0a4639 100644 --- a/code-generation/pom.xml +++ b/code-generation/pom.xml @@ -12,10 +12,16 @@ + + com.google.auto.value + auto-value-annotations + ${auto-value.version} + com.google.auto.value auto-value ${auto-value.version} + provided com.google.auto.factory @@ -43,9 +49,9 @@ - 1.3 - 1.0-beta5 - 1.0-rc5 + 1.6.6 + 1.0-beta6 + 1.0-rc6 4.2.0 diff --git a/code-generation/src/main/java/com/baeldung/autovalue/Person.java b/code-generation/src/main/java/com/baeldung/autovalue/Person.java new file mode 100644 index 0000000000..a5fb684596 --- /dev/null +++ b/code-generation/src/main/java/com/baeldung/autovalue/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.autovalue; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.google.auto.value.AutoValue; + +@AutoValue +public abstract class Person { + + public abstract String name(); + + public abstract List favoriteMovies(); + + public static Builder builder() { + return new AutoValue_Person.Builder(); + } + + @AutoValue.Builder + public static abstract class Builder { + + public abstract Builder name(String value); + + public abstract Builder favoriteMovies(List value); + + abstract List favoriteMovies(); + + abstract Person autoBuild(); + + public Person build() { + List favoriteMovies = favoriteMovies(); + List copy = Collections.unmodifiableList(new ArrayList<>(favoriteMovies)); + favoriteMovies(copy); + return autoBuild(); + } + } +} diff --git a/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java b/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java new file mode 100644 index 0000000000..fce12edafe --- /dev/null +++ b/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.autovalue; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +/** + * Unit Test which verifies that the {@link Person} value object creates defensive copies of its favoriteMovies list. + */ +public class PersonUnitTest { + + @Test + public void givenNewPerson_whenModifyOriginalList_thenValueObjectIsNotAlsoModified() { + // GIVEN new Person + List originalFavoriteMoviesList = new ArrayList(); + originalFavoriteMoviesList.add("Training Day"); + originalFavoriteMoviesList.add("Fast and the Furious"); + Person person = Person.builder() + .name("Dan") + .favoriteMovies(originalFavoriteMoviesList) + .build(); + + // WHEN modify original list + originalFavoriteMoviesList.add("Friday"); + + // THEN Person remains unaffected + assertFalse(person.favoriteMovies() + .contains("Friday")); + assertEquals(2, person.favoriteMovies() + .size()); + } + +} diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index f1984f18f4..95a00a1f5b 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts - [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings) - [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming) - [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services) +- [Categories in Groovy](https://www.baeldung.com/groovy-categories) - [[<-- Prev]](/core-groovy) diff --git a/core-groovy-collections/README.md b/core-groovy-collections/README.md index 4afd214e7d..aae8be508e 100644 --- a/core-groovy-collections/README.md +++ b/core-groovy-collections/README.md @@ -5,4 +5,6 @@ This module contains articles about Groovy core collections ## Relevant articles: - [Maps in Groovy](https://www.baeldung.com/groovy-maps) - +- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements) +- [Lists in Groovy](https://www.baeldung.com/groovy-lists) +- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy similarity index 95% rename from core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy index 9617c099ce..82a2138be4 100644 --- a/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy @@ -1,11 +1,11 @@ -package com.baeldung.lists +package com.baeldung.find -import com.baeldung.Person +import com.baeldung.find.Person import org.junit.Test import static org.junit.Assert.* -class ListUnitTest { +class ListFindUnitTest { private final personList = [ new Person("Regina", "Fitzpatrick", 25), diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy similarity index 53% rename from core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy index 0d6bbed04b..16e231182b 100644 --- a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy @@ -1,11 +1,11 @@ -package com.baeldung.map +package com.baeldung.find -import com.baeldung.Person +import com.baeldung.find.Person import org.junit.Test import static org.junit.Assert.* -class MapUnitTest { +class MapFindUnitTest { private final personMap = [ Regina : new Person("Regina", "Fitzpatrick", 25), @@ -13,84 +13,6 @@ class MapUnitTest { Lucian : new Person("Lucian", "Walter", 30) ] - @Test - void whenUsingEach_thenMapIsIterated() { - def map = [ - 'FF0000' : 'Red', - '00FF00' : 'Lime', - '0000FF' : 'Blue', - 'FFFF00' : 'Yellow' - ] - - map.each { println "Hex Code: $it.key = Color Name: $it.value" } - } - - @Test - void whenUsingEachWithEntry_thenMapIsIterated() { - def map = [ - 'E6E6FA' : 'Lavender', - 'D8BFD8' : 'Thistle', - 'DDA0DD' : 'Plum', - ] - - map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" } - } - - @Test - void whenUsingEachWithKeyAndValue_thenMapIsIterated() { - def map = [ - '000000' : 'Black', - 'FFFFFF' : 'White', - '808080' : 'Gray' - ] - - map.each { key, val -> - println "Hex Code: $key = Color Name $val" - } - } - - @Test - void whenUsingEachWithIndexAndEntry_thenMapIsIterated() { - def map = [ - '800080' : 'Purple', - '4B0082' : 'Indigo', - '6A5ACD' : 'Slate Blue' - ] - - map.eachWithIndex { entry, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") - println "$indent Hex Code: $entry.key = Color Name: $entry.value" - } - } - - @Test - void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() { - def map = [ - 'FFA07A' : 'Light Salmon', - 'FF7F50' : 'Coral', - 'FF6347' : 'Tomato', - 'FF4500' : 'Orange Red' - ] - - map.eachWithIndex { key, val, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") - println "$indent Hex Code: $key = Color Name: $val" - } - } - - @Test - void whenUsingForLoop_thenMapIsIterated() { - def map = [ - '2E8B57' : 'Seagreen', - '228B22' : 'Forest Green', - '008000' : 'Green' - ] - - for (entry in map) { - println "Hex Code: $entry.key = Color Name: $entry.value" - } - } - @Test void whenMapContainsKeyElement_thenCheckReturnsTrue() { def map = [a: 'd', b: 'e', c: 'f'] diff --git a/core-groovy/src/main/groovy/com/baeldung/Person.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy similarity index 96% rename from core-groovy/src/main/groovy/com/baeldung/Person.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy index 6a009aeee0..e65826363a 100644 --- a/core-groovy/src/main/groovy/com/baeldung/Person.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy @@ -1,4 +1,4 @@ -package com.baeldung +package com.baeldung.find class Person { private String firstname diff --git a/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy similarity index 83% rename from core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy index 1248c9ac91..d2d03d5427 100644 --- a/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy @@ -1,10 +1,10 @@ -package com.baeldung.set +package com.baeldung.find import org.junit.Test import static org.junit.Assert.assertTrue -class SetUnitTest { +class SetFindUnitTest { @Test void whenSetContainsElement_thenCheckReturnsTrue() { diff --git a/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy new file mode 100644 index 0000000000..970203ce85 --- /dev/null +++ b/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy @@ -0,0 +1,87 @@ +package com.baeldung.iteratemap + +import com.baeldung.find.Person +import org.junit.Test + +import static org.junit.Assert.* + +class IterateMapUnitTest { + + @Test + void whenUsingEach_thenMapIsIterated() { + def map = [ + 'FF0000' : 'Red', + '00FF00' : 'Lime', + '0000FF' : 'Blue', + 'FFFF00' : 'Yellow' + ] + + map.each { println "Hex Code: $it.key = Color Name: $it.value" } + } + + @Test + void whenUsingEachWithEntry_thenMapIsIterated() { + def map = [ + 'E6E6FA' : 'Lavender', + 'D8BFD8' : 'Thistle', + 'DDA0DD' : 'Plum', + ] + + map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" } + } + + @Test + void whenUsingEachWithKeyAndValue_thenMapIsIterated() { + def map = [ + '000000' : 'Black', + 'FFFFFF' : 'White', + '808080' : 'Gray' + ] + + map.each { key, val -> + println "Hex Code: $key = Color Name $val" + } + } + + @Test + void whenUsingEachWithIndexAndEntry_thenMapIsIterated() { + def map = [ + '800080' : 'Purple', + '4B0082' : 'Indigo', + '6A5ACD' : 'Slate Blue' + ] + + map.eachWithIndex { entry, index -> + def indent = ((index == 0 || index % 2 == 0) ? " " : "") + println "$indent Hex Code: $entry.key = Color Name: $entry.value" + } + } + + @Test + void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() { + def map = [ + 'FFA07A' : 'Light Salmon', + 'FF7F50' : 'Coral', + 'FF6347' : 'Tomato', + 'FF4500' : 'Orange Red' + ] + + map.eachWithIndex { key, val, index -> + def indent = ((index == 0 || index % 2 == 0) ? " " : "") + println "$indent Hex Code: $key = Color Name: $val" + } + } + + @Test + void whenUsingForLoop_thenMapIsIterated() { + def map = [ + '2E8B57' : 'Seagreen', + '228B22' : 'Forest Green', + '008000' : 'Green' + ] + + for (entry in map) { + println "Hex Code: $entry.key = Color Name: $entry.value" + } + } +} diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy similarity index 98% rename from core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy index 7771028132..e4c0a0c177 100644 --- a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy @@ -1,9 +1,9 @@ -package com.baeldung.groovy.lists +package com.baeldung.lists import static groovy.test.GroovyAssert.* import org.junit.Test -class ListTest{ +class ListUnitTest { @Test void testCreateList() { diff --git a/core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy similarity index 99% rename from core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy rename to core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy index c6105eb1c4..deb552c420 100644 --- a/core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy +++ b/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.maps; import static groovy.test.GroovyAssert.* import org.junit.Test diff --git a/core-groovy/README.md b/core-groovy/README.md index 0f45eed879..25a0aece3a 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -8,11 +8,8 @@ This module contains articles about core Groovy concepts - [Working with JSON in Groovy](https://www.baeldung.com/groovy-json) - [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read) - [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings) -- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating) - [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits) - [Closures in Groovy](https://www.baeldung.com/groovy-closures) -- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements) -- [Lists in Groovy](https://www.baeldung.com/groovy-lists) - [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date) - [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io) - [[More -->]](/core-groovy-2) \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy b/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy deleted file mode 100644 index f1d528207f..0000000000 --- a/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy +++ /dev/null @@ -1,148 +0,0 @@ -package com.baeldung.groovy.map; - -import static groovy.test.GroovyAssert.* -import org.junit.Test - -class MapTest{ - - @Test - void createMap() { - - def emptyMap = [:] - assertNotNull(emptyMap) - - assertTrue(emptyMap instanceof java.util.LinkedHashMap) - - def map = [name:"Jerry", age: 42, city: "New York"] - assertTrue(map.size() == 3) - } - - @Test - void addItemsToMap() { - - def map = [name:"Jerry"] - - map["age"] = 42 - - map.city = "New York" - - def hobbyLiteral = "hobby" - def hobbyMap = [(hobbyLiteral): "Singing"] - map.putAll(hobbyMap) - - assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]) - assertTrue(hobbyMap.hobby == "Singing") - assertTrue(hobbyMap[hobbyLiteral] == "Singing") - - map.plus([1:20]) // returns new map - - map << [2:30] - - } - - @Test - void getItemsFromMap() { - - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - assertTrue(map["name"] == "Jerry") - - assertTrue(map.name == "Jerry") - - def propertyAge = "age" - assertTrue(map[propertyAge] == 42) - } - - @Test - void removeItemsFromMap() { - - def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49] - - def minusMap = map.minus([2:42, 4:34]); - assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49]) - - minusMap.removeAll{it -> it.key instanceof String} - assertTrue( minusMap == [ 1:20, 6:39, 7:49]) - - minusMap.retainAll{it -> it.value %2 == 0} - assertTrue( minusMap == [1:20]) - } - - @Test - void iteratingOnMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - map.each{ entry -> println "$entry.key: $entry.value" } - - map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" } - - map.eachWithIndex{ key, value, i -> println "$i $key: $value" } - } - - @Test - void filteringAndSearchingMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - assertTrue(map.find{ it.value == "New York"}.key == "city") - - assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"]) - - map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")} - - assertTrue(map.every{it -> it.value instanceof String} == false) - - assertTrue(map.any{it -> it.value instanceof String} == true) - } - - @Test - void collect(){ - - def map = [1: [name:"Jerry", age: 42, city: "New York"], - 2: [name:"Long", age: 25, city: "New York"], - 3: [name:"Dustin", age: 29, city: "New York"], - 4: [name:"Dustin", age: 34, city: "New York"]] - - def names = map.collect{entry -> entry.value.name} // returns only list - assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"]) - - def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name} - assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set) - - def idNames = map.collectEntries{key, value -> [key, value.name]} - assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"]) - - def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name} - assertTrue(below30Names == ["Long", "Dustin"]) - - - } - - @Test - void group(){ - def map = [1:20, 2: 40, 3: 11, 4: 93] - - def subMap = map.groupBy{it.value % 2} - println subMap - assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]]) - - def keySubMap = map.subMap([1, 2]) - assertTrue(keySubMap == [1:20, 2:40]) - - } - - @Test - void sorting(){ - def map = [ab:20, a: 40, cb: 11, ba: 93] - - def naturallyOrderedMap = map.sort() - assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap) - - def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator) - assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap) - - def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value }) - assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap) - - } - -} diff --git a/core-java-modules/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/README.md b/core-java-modules/core-java-arrays-2/README.md index 5fa2f2bf4c..a78b3327b6 100644 --- a/core-java-modules/core-java-arrays-2/README.md +++ b/core-java-modules/core-java-arrays-2/README.md @@ -12,4 +12,5 @@ This module contains articles about Java arrays - [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) - [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element) - [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element) +- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list) - [[<-- Prev]](/core-java-modules/core-java-arrays) diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md index 13ca191edb..de5daddb38 100644 --- a/core-java-modules/core-java-collections-2/README.md +++ b/core-java-modules/core-java-collections-2/README.md @@ -12,4 +12,4 @@ - [Sorting in Java](https://www.baeldung.com/java-sorting) - [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size) - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) - +- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) diff --git a/core-java-modules/core-java-collections-list-2/README.md b/core-java-modules/core-java-collections-list-2/README.md index fada9d96ac..0d2da41b41 100644 --- a/core-java-modules/core-java-collections-list-2/README.md +++ b/core-java-modules/core-java-collections-list-2/README.md @@ -11,4 +11,5 @@ This module contains articles about the Java List collection - [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list) - [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) - [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) -- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3) \ No newline at end of file +- [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist) +- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3) diff --git a/core-java-modules/core-java-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-date-operations/pom.xml b/core-java-modules/core-java-date-operations/pom.xml new file mode 100644 index 0000000000..f6e75ca518 --- /dev/null +++ b/core-java-modules/core-java-date-operations/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + core-java-date-operations + ${project.parent.version} + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java new file mode 100644 index 0000000000..ab1550fd90 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/CalendarUtils.java @@ -0,0 +1,15 @@ +package com.baeldung.datetime; + +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; + +public class CalendarUtils { + + public static Calendar getPlusDays(Date date, int amount) throws ParseException { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.DAY_OF_YEAR, amount); + return calendar; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java new file mode 100644 index 0000000000..34f799d3f4 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/DateUtils.java @@ -0,0 +1,20 @@ +package com.baeldung.datetime; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class DateUtils { + + public static Date getNow() { + return new Date(); + } + + public static Date getDate(long millis) { + return new Date(millis); + } + + public static Date getDate(String dateAsString, String pattern) throws ParseException { + return new SimpleDateFormat(pattern).parse(dateAsString); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java new file mode 100644 index 0000000000..1b4e825df8 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/DateUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime.sql; + +import java.sql.Date; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class DateUtils { + + public static Date getNow() { + return new Date(System.currentTimeMillis()); + } + + public static Date getDate(String dateAsString) { + return Date.valueOf(dateAsString); + } + + public static Date getDate(String dateAsString, String pattern) throws ParseException { + java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString); + return new Date(customUtilDate.getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java new file mode 100644 index 0000000000..3fa1ffdef8 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimeUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime.sql; + +import java.sql.Time; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class TimeUtils { + + public static Time getNow() { + return new Time(System.currentTimeMillis()); + } + + public static Time getTime(String timeAsString) { + return Time.valueOf(timeAsString); + } + + public static Time getTime(String dateAsString, String pattern) throws ParseException { + java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString); + return new Time(customUtilDate.getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java new file mode 100644 index 0000000000..02a928daa7 --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/main/java/com/baeldung/datetime/sql/TimestampUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime.sql; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class TimestampUtils { + + public static Timestamp getNow() { + return new Timestamp(System.currentTimeMillis()); + } + + public static Timestamp getTimestamp(String timestampAsString) { + return Timestamp.valueOf(timestampAsString); + } + + public static Timestamp getTimestamp(String dateAsString, String pattern) throws ParseException { + java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString); + return new Timestamp(customUtilDate.getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java new file mode 100644 index 0000000000..0060162ffb --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/CalendarUtilsUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.CalendarUtils; +import com.baeldung.datetime.DateUtils; + +import java.text.ParseException; +import java.util.Date; + +public class CalendarUtilsUnitTest { + + @Test + public void givenDateAndDaysToAdd_thenCalendarIsCorrectlyReturned() throws ParseException { + Date initialDate = DateUtils.getDate("2020/01/01", "yyyy/MM/dd"); + Date expectedDate= DateUtils.getDate("2020/01/11", "yyyy/MM/dd"); + assertEquals(expectedDate, CalendarUtils.getPlusDays(initialDate, 10).getTime()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java new file mode 100644 index 0000000000..62a0fc0b4b --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/DateUtilsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.datetime; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.DateUtils; + +import java.text.ParseException; +import java.util.Date; + +public class DateUtilsUnitTest { + + @Test + public void givenTimeMillis_thenDateIsReturned() { + Date now = DateUtils.getNow(); + assertEquals(DateUtils.getDate(now.getTime()), now); + } + + @Test + public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { + long milliseconds = new Date(2020 - 1900, 0, 1).getTime(); + assertEquals(DateUtils.getDate(milliseconds), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java new file mode 100644 index 0000000000..a04f64f6dd --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/DateUtilsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.datetime.sql; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.sql.DateUtils; + +import java.text.ParseException; +import java.util.Date; + +public class DateUtilsUnitTest { + + @Test + public void givenCurrentDate_thenTodayIsReturned() { + assertEquals(DateUtils.getNow(), new Date()); + } + + @Test(expected = IllegalArgumentException.class) + public void givenDateAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + DateUtils.getDate("2020 01 01"); + } + + @Test + public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException { + assertEquals(DateUtils.getDate("2020-01-01"), DateUtils.getDate("2020/01/01", "yyyy/MM/dd")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java new file mode 100644 index 0000000000..6b49558f1b --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimeUtilsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.datetime.sql; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.sql.TimeUtils; + +import java.text.ParseException; +import java.util.Date; + +public class TimeUtilsUnitTest { + + @Test + public void givenCurrentTime_thenNowIsReturned() { + assertEquals(TimeUtils.getNow(), new Date()); + } + + @Test(expected = IllegalArgumentException.class) + public void givenTimeAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + TimeUtils.getTime("10 11 12"); + } + + @Test + public void givenTimeAndPattern_thenTimeIsCorrectlyReturned() throws ParseException { + assertEquals(TimeUtils.getTime("10:11:12"), TimeUtils.getTime("10 11 12", "hh mm ss")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java new file mode 100644 index 0000000000..2faf8fab0e --- /dev/null +++ b/core-java-modules/core-java-date-operations/src/test/java/com/baeldung/datetime/sql/TimestampUtilsUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.datetime.sql; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.datetime.sql.TimestampUtils; + +import java.text.ParseException; +import java.util.Date; + +public class TimestampUtilsUnitTest { + + @Test + public void givenCurrentTimestamp_thenNowIsReturned() { + assertEquals(TimestampUtils.getNow() + .getTime(), new Date().getTime()); + } + + @Test(expected = IllegalArgumentException.class) + public void givenTimestampAsString_whenPatternIsNotRespected_thenExceptionIsThrown() { + TimestampUtils.getTimestamp("2020/01/01 10:11-12"); + } + + @Test + public void givenTimestampAndPattern_thenTimestampIsCorrectlyReturned() throws ParseException { + assertEquals(TimestampUtils.getTimestamp("2020-01-01 10:11:12"), TimestampUtils.getTimestamp("2020/01/01 10:11-12", "yyyy/MM/dd hh:mm-ss")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-computations/README.md b/core-java-modules/core-java-datetime-computations/README.md new file mode 100644 index 0000000000..591ddeaa94 --- /dev/null +++ b/core-java-modules/core-java-datetime-computations/README.md @@ -0,0 +1,15 @@ +## Java Date/time computations Cookbooks and Examples + +This module contains articles about date and time computations in Java. + +### Relevant Articles: +- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) +- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) +- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) +- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) +- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) +- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) +- [Calculate Age in Java](http://www.baeldung.com/java-get-age) +- [Increment Date in Java](http://www.baeldung.com/java-increment-date) +- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) +- [Introduction to Joda-Time](http://www.baeldung.com/joda-time) diff --git a/core-java-modules/core-java-datetime-computations/pom.xml b/core-java-modules/core-java-datetime-computations/pom.xml new file mode 100644 index 0000000000..934df8018f --- /dev/null +++ b/core-java-modules/core-java-datetime-computations/pom.xml @@ -0,0 +1,71 @@ + + 4.0.0 + core-java-datetime-computations + ${project.parent.version} + core-java-datetime-computations + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + joda-time + joda-time + ${joda-time.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.darwinsys + hirondelle-date4j + RELEASE + test + + + + + core-java-datetime-computations + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 2.10 + + 3.6.1 + 1.9 + 1.9 + + diff --git a/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/AgeCalculator.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/AgeCalculator.java diff --git a/java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/DateWithoutTime.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/date/DateWithoutTime.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/AddHoursToDate.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/AddHoursToDate.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java index a6cef94377..8b6d9885af 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/DateExtractYearMonthDayIntegerValues.java @@ -1,28 +1,28 @@ -package com.baeldung.datetime; - -import java.util.Calendar; -import java.util.Date; - -public class DateExtractYearMonthDayIntegerValues { - - int getYear(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - return calendar.get(Calendar.YEAR); - } - - int getMonth(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - return calendar.get(Calendar.MONTH); - } - - int getDay(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - - return calendar.get(Calendar.DAY_OF_MONTH); - } -} +package com.baeldung.datetime; + +import java.util.Calendar; +import java.util.Date; + +public class DateExtractYearMonthDayIntegerValues { + + int getYear(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.YEAR); + } + + int getMonth(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.MONTH); + } + + int getDay(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + return calendar.get(Calendar.DAY_OF_MONTH); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java index b40e10f6ad..6daa86130d 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.LocalDate; - -public class LocalDateExtractYearMonthDayIntegerValues { - - int getYear(LocalDate localDate) { - return localDate.getYear(); - } - - int getMonth(LocalDate localDate) { - return localDate.getMonthValue(); - } - - int getDay(LocalDate localDate) { - return localDate.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.LocalDate; + +public class LocalDateExtractYearMonthDayIntegerValues { + + int getYear(LocalDate localDate) { + return localDate.getYear(); + } + + int getMonth(LocalDate localDate) { + return localDate.getMonthValue(); + } + + int getDay(LocalDate localDate) { + return localDate.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java index 404a62d2f4..bb4415fbc7 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/LocalDateTimeExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.LocalDateTime; - -public class LocalDateTimeExtractYearMonthDayIntegerValues { - - int getYear(LocalDateTime localDateTime) { - return localDateTime.getYear(); - } - - int getMonth(LocalDateTime localDateTime) { - return localDateTime.getMonthValue(); - } - - int getDay(LocalDateTime localDateTime) { - return localDateTime.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.LocalDateTime; + +public class LocalDateTimeExtractYearMonthDayIntegerValues { + + int getYear(LocalDateTime localDateTime) { + return localDateTime.getYear(); + } + + int getMonth(LocalDateTime localDateTime) { + return localDateTime.getMonthValue(); + } + + int getDay(LocalDateTime localDateTime) { + return localDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java similarity index 96% rename from java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java index e686b05493..398c03102c 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.OffsetDateTime; - -public class OffsetDateTimeExtractYearMonthDayIntegerValues { - - int getYear(OffsetDateTime offsetDateTime) { - return offsetDateTime.getYear(); - } - - int getMonth(OffsetDateTime offsetDateTime) { - return offsetDateTime.getMonthValue(); - } - - int getDay(OffsetDateTime offsetDateTime) { - return offsetDateTime.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.OffsetDateTime; + +public class OffsetDateTimeExtractYearMonthDayIntegerValues { + + int getYear(OffsetDateTime offsetDateTime) { + return offsetDateTime.getYear(); + } + + int getMonth(OffsetDateTime offsetDateTime) { + return offsetDateTime.getMonthValue(); + } + + int getDay(OffsetDateTime offsetDateTime) { + return offsetDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java similarity index 95% rename from java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java index 3e790b2b3f..86bce90f75 100644 --- a/java-dates/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java +++ b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/ZonedDateTimeExtractYearMonthDayIntegerValues.java @@ -1,18 +1,18 @@ -package com.baeldung.datetime; - -import java.time.ZonedDateTime; - -public class ZonedDateTimeExtractYearMonthDayIntegerValues { - - int getYear(ZonedDateTime zonedDateTime) { - return zonedDateTime.getYear(); - } - - int getMonth(ZonedDateTime zonedDateTime) { - return zonedDateTime.getMonthValue(); - } - - int getDay(ZonedDateTime zonedDateTime) { - return zonedDateTime.getDayOfMonth(); - } -} +package com.baeldung.datetime; + +import java.time.ZonedDateTime; + +public class ZonedDateTimeExtractYearMonthDayIntegerValues { + + int getYear(ZonedDateTime zonedDateTime) { + return zonedDateTime.getYear(); + } + + int getMonth(ZonedDateTime zonedDateTime) { + return zonedDateTime.getMonthValue(); + } + + int getDay(ZonedDateTime zonedDateTime) { + return zonedDateTime.getDayOfMonth(); + } +} diff --git a/java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/datetime/modify/DateIncrementer.java diff --git a/java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/gregorian/calendar/GregorianCalendarExample.java diff --git a/java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java b/core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/java9/time/TimeApi.java rename to core-java-modules/core-java-datetime-computations/src/main/java/com/baeldung/java9/time/TimeApi.java diff --git a/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java rename to core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/core-java-modules/core-java-datetime-computations/src/test/java/com/baeldung/date/DateDiffUnitTest.java similarity index 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-java8/README.md b/core-java-modules/core-java-datetime-java8/README.md new file mode 100644 index 0000000000..044f6f3fe3 --- /dev/null +++ b/core-java-modules/core-java-datetime-java8/README.md @@ -0,0 +1,15 @@ +## Java 8+ Date and Time API + +This module contains articles about the Date and Time API introduced with Java 8. + +### Relevant Articles: +- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) +- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) +- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) +- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) +- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) +- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) +- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) +- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) +- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone) +- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates) diff --git a/java-dates/pom.xml b/core-java-modules/core-java-datetime-java8/pom.xml similarity index 83% rename from java-dates/pom.xml rename to core-java-modules/core-java-datetime-java8/pom.xml index 761ebd71a6..72d51b5f10 100644 --- a/java-dates/pom.xml +++ b/core-java-modules/core-java-datetime-java8/pom.xml @@ -1,17 +1,16 @@ 4.0.0 - com.baeldung - java-dates - 0.1.0-SNAPSHOT - java-dates + core-java-datetime-java8 + ${project.parent.version} + core-java-datetime-java8 jar com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java @@ -21,11 +20,10 @@ ${commons-lang3.version} - log4j - log4j - ${log4j.version} + joda-time + joda-time + ${joda-time.version} - org.assertj assertj-core @@ -33,20 +31,15 @@ test - joda-time - joda-time - ${joda-time.version} - - - com.darwinsys - hirondelle-date4j - RELEASE + log4j + log4j + ${log4j.version} test - java-dates + core-java-datetime-java8 src/main/resources @@ -68,10 +61,10 @@ + 1.9 + 1.9 2.10 3.6.1 - 1.9 - 1.9 diff --git a/java-dates/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java diff --git a/java-dates/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 100% rename from java-dates/src/main/java/com/baeldung/datetime/UseDuration.java rename to core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java diff --git a/java-dates/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 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/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java similarity index 85% rename from java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java index ff51476e7c..af72f9e58a 100644 --- a/java-dates/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java +++ b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java @@ -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/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java diff --git a/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-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index ba327b06f2..f7b0c37e73 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -12,4 +12,8 @@ This module contains articles about core java exceptions - [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws) - [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error) - [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions) - +- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) +- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler) +- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions) +- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) +- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java new file mode 100644 index 0000000000..fee52fe2bc --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java @@ -0,0 +1,16 @@ +package com.baeldung.trywithresource; + +public class AutoCloseableMain { + + public static void main(String[] args) throws Exception { + orderOfClosingResources(); + } + + private static void orderOfClosingResources() throws Exception { + try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); + AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { + af.doSomething(); + as.doSomething(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java new file mode 100644 index 0000000000..b001244d93 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java @@ -0,0 +1,17 @@ +package com.baeldung.trywithresource; + +public class AutoCloseableResourcesFirst implements AutoCloseable { + + public AutoCloseableResourcesFirst() { + System.out.println("Constructor -> AutoCloseableResources_First"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_First"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_First"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java new file mode 100644 index 0000000000..ef8bcd7166 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java @@ -0,0 +1,17 @@ +package com.baeldung.trywithresource; + +public class AutoCloseableResourcesSecond implements AutoCloseable { + + public AutoCloseableResourcesSecond() { + System.out.println("Constructor -> AutoCloseableResources_Second"); + } + + public void doSomething() { + System.out.println("Something -> AutoCloseableResources_Second"); + } + + @Override + public void close() throws Exception { + System.out.println("Closed AutoCloseableResources_Second"); + } +} diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java new file mode 100644 index 0000000000..3ddf0f52e0 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java @@ -0,0 +1,8 @@ +package com.baeldung.trywithresource; + +public class MyResource implements AutoCloseable { + @Override + public void close() throws Exception { + System.out.println("Closed MyResource"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/README.md b/core-java-modules/core-java-io-2/README.md index 2299320f32..867b7ad732 100644 --- a/core-java-modules/core-java-io-2/README.md +++ b/core-java-modules/core-java-io-2/README.md @@ -3,4 +3,5 @@ - [Create a File in a Specific Directory in Java](https://www.baeldung.com/java-create-file-in-directory) - [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader) - +- [The Java File Class](https://www.baeldung.com/java-io-file) +- [Java FileWriter](https://www.baeldung.com/java-filewriter) diff --git a/core-java-modules/core-java-io-2/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java new file mode 100644 index 0000000000..8653b1e137 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/scanner/HasNextVsHasNextLineDemo.java @@ -0,0 +1,96 @@ +package com.baeldung.scanner; + +import lombok.extern.log4j.Log4j; +import org.apache.log4j.LogManager; +import org.apache.log4j.PropertyConfigurator; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.Scanner; + +@Log4j +public class HasNextVsHasNextLineDemo { + private static final String LINE = "----------------------------"; + private static final String END_LINE = "--------OUTPUT--END---------\n"; + + + private static final String INPUT = new StringBuilder() + .append("magic\tproject\n") + .append(" database: oracle\n") + .append("dependencies:\n") + .append("spring:foo:bar\n") + .append("\n").toString(); + + private static void hasNextBasic() { + printHeader("hasNext() Basic"); + Scanner scanner = new Scanner(INPUT); + while (scanner.hasNext()) { + log.info(scanner.next()); + } + log.info(END_LINE); + scanner.close(); + } + + private static void hasNextWithDelimiter() { + printHeader("hasNext() with delimiter"); + Scanner scanner = new Scanner(INPUT); + while (scanner.hasNext()) { + String token = scanner.next(); + if ("dependencies:".equals(token)) { + scanner.useDelimiter(":"); + } + log.info(token); + } + log.info(END_LINE); + scanner.close(); + } + + private static void hasNextWithDelimiterFixed() { + printHeader("hasNext() with delimiter FIX"); + Scanner scanner = new Scanner(INPUT); + while (scanner.hasNext()) { + String token = scanner.next(); + if ("dependencies:".equals(token)) { + scanner.useDelimiter(":|\\s+"); + } + log.info(token); + } + log.info(END_LINE); + scanner.close(); + } + + private static void addLineNumber() { + printHeader("add line number by hasNextLine() "); + Scanner scanner = new Scanner(INPUT); + int i = 0; + while (scanner.hasNextLine()) { + log.info(String.format("%d|%s", ++i, scanner.nextLine())); + } + log.info(END_LINE); + scanner.close(); + } + + private static void printHeader(String title) { + log.info(LINE); + log.info(title); + log.info(LINE); + } + + public static void main(String[] args) throws IOException { + setLogger(); + hasNextBasic(); + hasNextWithDelimiter(); + hasNextWithDelimiterFixed(); + addLineNumber(); + } + + //overwrite the logger config + private static void setLogger() throws IOException { + InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties"); + Properties props = new Properties(); + props.load(is); + LogManager.resetConfiguration(); + PropertyConfigurator.configure(props); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/src/main/resources/scanner/log4j.properties b/core-java-modules/core-java-io-2/src/main/resources/scanner/log4j.properties new file mode 100644 index 0000000000..59cb116bff --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/resources/scanner/log4j.properties @@ -0,0 +1,4 @@ +log4j.rootLogger=INFO, A1 +log4j.appender.A1=org.apache.log4j.ConsoleAppender +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=[DEMO]%m%n diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java new file mode 100644 index 0000000000..471c0ea1c7 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/scanner/JavaScannerUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.scanner; + +import static org.junit.Assert.assertEquals; + +import java.util.NoSuchElementException; +import java.util.Scanner; + +import org.junit.Test; + +public class JavaScannerUnitTest { + + @Test + public void whenReadingLines_thenCorrect() { + String input = "Scanner\nTest\n"; + try (Scanner scanner = new Scanner(input)) { + assertEquals("Scanner", scanner.nextLine()); + assertEquals("Test", scanner.nextLine()); + } + } + + @Test + public void whenReadingPartialLines_thenCorrect() { + String input = "Scanner\n"; + try (Scanner scanner = new Scanner(input)) { + scanner.useDelimiter(""); + scanner.next(); + assertEquals("canner", scanner.nextLine()); + } + } + + @Test(expected = NoSuchElementException.class) + public void givenNoNewLine_whenReadingNextLine_thenThrowNoSuchElementException() { + try (Scanner scanner = new Scanner("")) { + String result = scanner.nextLine(); + } + } + + @Test(expected = IllegalStateException.class) + public void givenScannerIsClosed_whenReadingNextLine_thenThrowIllegalStateException() { + Scanner scanner = new Scanner(""); + scanner.close(); + String result = scanner.nextLine(); + } +} diff --git a/core-java-modules/core-java-io/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-jvm/README.md b/core-java-modules/core-java-jvm/README.md index a1a57c83c5..89600ad924 100644 --- a/core-java-modules/core-java-jvm/README.md +++ b/core-java-modules/core-java-jvm/README.md @@ -1,8 +1,12 @@ -========= - ## Core Java JVM Cookbooks and Examples +This module contains articles about working with the Java Virtual Machine (JVM). + ### Relevant Articles: + - [Method Inlining in the JVM](https://www.baeldung.com/jvm-method-inlining) +- [JVM Log Forging](https://www.baeldung.com/jvm-log-forging) +- [Guide to Java Instrumentation](https://www.baeldung.com/java-instrumentation) +- [Class Loaders in Java](https://www.baeldung.com/java-classloaders) - [A Guide to System.exit()](https://www.baeldung.com/java-system-exit) - [Guide to System.gc()](https://www.baeldung.com/java-system-gc) diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 8e8271f09b..74960820d7 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -13,4 +13,49 @@ ../../ + + + junit + junit + ${junit.version} + test + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.javassist + javassist + ${javaassist.version} + + + org.owasp.esapi + esapi + ${esapi.version} + + + com.sun + tools + ${sun.tools.version} + system + ${java.home}/../lib/tools.jar + + + + + + 3.6.1 + + 3.21.0-GA + 2.1.0.1 + 1.8.0 + diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/CustomClassLoader.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/classloader/CustomClassLoader.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/CustomClassLoader.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/classloader/PrintClassLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/classloader/PrintClassLoader.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/AtmTransformer.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/agent/MyInstrumentationAgent.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/AgentLoader.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/Launcher.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/Launcher.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/Launcher.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtm.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtm.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtm.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/instrumentation/application/MyAtmApplication.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/logforging/LogForgingDemo.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/logforging/LogForgingDemo.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/logforging/LogForgingDemo.java rename to core-java-modules/core-java-jvm/src/main/java/com/baeldung/logforging/LogForgingDemo.java diff --git a/core-java-modules/core-java/src/main/resources/ESAPI.properties b/core-java-modules/core-java-jvm/src/main/resources/ESAPI.properties similarity index 100% rename from core-java-modules/core-java/src/main/resources/ESAPI.properties rename to core-java-modules/core-java-jvm/src/main/resources/ESAPI.properties diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java rename to core-java-modules/core-java-jvm/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-3/README.md b/core-java-modules/core-java-lang-oop-3/README.md index 4ac6c3ffe9..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/README.md b/core-java-modules/core-java-lang-syntax-2/README.md index a3b11865af..538a29181a 100644 --- a/core-java-modules/core-java-lang-syntax-2/README.md +++ b/core-java-modules/core-java-lang-syntax-2/README.md @@ -11,4 +11,5 @@ This module contains articles about Java syntax - [Java Double Brace Initialization](https://www.baeldung.com/java-double-brace-initialization) - [The Java Native Keyword and Methods](https://www.baeldung.com/java-native) - [Variable Scope in Java](https://www.baeldung.com/java-variable-scope) +- [Java ‘protected’ Access Modifier](https://www.baeldung.com/java-protected-access-modifier) - [[<-- Prev]](/core-java-modules/core-java-lang-syntax) diff --git a/core-java-modules/core-java-lang/README.md b/core-java-modules/core-java-lang/README.md index 9b485d80e9..9e98bb849b 100644 --- a/core-java-modules/core-java-lang/README.md +++ b/core-java-modules/core-java-lang/README.md @@ -13,4 +13,7 @@ This module contains articles about core features in the Java language - [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic) - [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name) - [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values) -- [[More --> ]](/core-java-modules/core-java-lang-2) \ No newline at end of file +- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break) +- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) +- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java) +- [[More --> ]](/core-java-modules/core-java-lang-2) diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md index c384a28b64..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 8c5f7fe1e9..f09b62ebf2 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -42,6 +42,16 @@ ${assertj.version} test + + org.unix4j + unix4j-command + ${unix4j.version} + + + com.googlecode.grep4j + grep4j + ${grep4j.version} + @@ -77,5 +87,7 @@ 1.9 1.9 25.1-jre + 0.4 + 1.8.7 diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/printscreen/Screenshot.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java rename to core-java-modules/core-java-os/src/main/java/com/baeldung/printscreen/Screenshot.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/system/DetectOS.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/system/DetectOS.java similarity index 100% rename from core-java-modules/core-java/src/main/java/com/baeldung/system/DetectOS.java rename to core-java-modules/core-java-os/src/main/java/com/baeldung/system/DetectOS.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/grep/GrepWithUnix4JIntegrationTest.java diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/printscreen/ScreenshotLiveTest.java diff --git a/core-java-modules/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java similarity index 98% rename from core-java-modules/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java index efd7dda70f..53e9364207 100644 --- a/core-java-modules/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.shell; +package com.baeldung.java.shell; import org.junit.Assert; import org.junit.Test; diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java diff --git a/core-java-modules/core-java-security-manager/README.md b/core-java-modules/core-java-security-manager/README.md new file mode 100644 index 0000000000..a4abe7f80a --- /dev/null +++ b/core-java-modules/core-java-security-manager/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) diff --git a/core-java-modules/core-java-streams-2/README.md b/core-java-modules/core-java-streams-2/README.md new file mode 100644 index 0000000000..2ff95045c3 --- /dev/null +++ b/core-java-modules/core-java-streams-2/README.md @@ -0,0 +1,16 @@ +## Core Java streams + +This module contains articles about the Stream API in Java. + +### Relevant Articles: +- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams) +- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction) +- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany) +- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) +- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) +- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api) +- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams) +- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection) +- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend) +- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) +- More articles: [[<-- prev>]](/../core-java-streams) [[next -->]](/../core-java-streams-3) diff --git a/java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml similarity index 84% rename from java-streams-2/pom.xml rename to core-java-modules/core-java-streams-2/pom.xml index 4cebd44427..20c028edaa 100644 --- a/java-streams-2/pom.xml +++ b/core-java-modules/core-java-streams-2/pom.xml @@ -1,49 +1,53 @@ - - - 4.0.0 - com.baeldung.javastreams2 - java-streams-2 - 1.0 - java-streams-2 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator.version} - - - junit - junit - ${junit.version} - test - jar - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - UTF-8 - 1.9 - 1.9 - 3.11.1 - + + + 4.0.0 + core-java-streams-2 + 1.0 + core-java-streams-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + log4j + log4j + ${log4j.version} + + + junit + junit + ${junit.version} + test + jar + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + UTF-8 + 1.9 + 1.9 + 3.11.1 + \ No newline at end of file diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java similarity index 97% rename from java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java index 79c557524d..62d080c32c 100644 --- a/java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/application/Application.java @@ -1,39 +1,39 @@ -package com.baeldung.reduce.application; - -import com.baeldung.reduce.entities.User; -import com.baeldung.reduce.utilities.NumberUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class Application { - - public static void main(String[] args) { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); - System.out.println(result1); - - int result2 = numbers.stream().reduce(0, Integer::sum); - System.out.println(result2); - - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); - System.out.println(result3); - - String result4 = letters.stream().reduce("", String::concat); - System.out.println(result4); - - String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); - System.out.println(result5); - - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result6); - - String result7 = letters.parallelStream().reduce("", String::concat); - System.out.println(result7); - - int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result8); - } -} +package com.baeldung.reduce.application; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Application { + + public static void main(String[] args) { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + System.out.println(result1); + + int result2 = numbers.stream().reduce(0, Integer::sum); + System.out.println(result2); + + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); + System.out.println(result3); + + String result4 = letters.stream().reduce("", String::concat); + System.out.println(result4); + + String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + System.out.println(result5); + + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result6); + + String result7 = letters.parallelStream().reduce("", String::concat); + System.out.println(result7); + + int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + System.out.println(result8); + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java similarity index 97% rename from java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java index af4a9276a9..ecb0347e96 100644 --- a/java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/benchmarks/JMHStreamReduceBenchMark.java @@ -1,52 +1,52 @@ -package com.baeldung.reduce.benchmarks; - -import com.baeldung.reduce.entities.User; -import java.util.ArrayList; -import java.util.List; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.RunnerException; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; - -@State(Scope.Thread) -@BenchmarkMode(Mode.AverageTime) -public class JMHStreamReduceBenchMark { - - private final List userList = createUsers(); - - public static void main(String[] args) throws RunnerException { - - Options options = new OptionsBuilder() - .include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1) - .forks(1).shouldFailOnError(true).shouldDoGC(true) - .jvmArgs("-server").build(); - new Runner(options).run(); - } - - private List createUsers() { - List users = new ArrayList<>(); - for (int i = 0; i <= 1000000; i++) { - users.add(new User("John" + i, i)); - } - return users; - } - - @Benchmark - public Integer executeReduceOnParallelizedStream() { - return this.userList - .parallelStream() - .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } - - @Benchmark - public Integer executeReduceOnSequentialStream() { - return this.userList - .stream() - .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } -} +package com.baeldung.reduce.benchmarks; + +import com.baeldung.reduce.entities.User; +import java.util.ArrayList; +import java.util.List; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +public class JMHStreamReduceBenchMark { + + private final List userList = createUsers(); + + public static void main(String[] args) throws RunnerException { + + Options options = new OptionsBuilder() + .include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } + + private List createUsers() { + List users = new ArrayList<>(); + for (int i = 0; i <= 1000000; i++) { + users.add(new User("John" + i, i)); + } + return users; + } + + @Benchmark + public Integer executeReduceOnParallelizedStream() { + return this.userList + .parallelStream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } + + @Benchmark + public Integer executeReduceOnSequentialStream() { + return this.userList + .stream() + .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + } +} diff --git a/java-streams/src/main/java/com/baeldung/reduce/entities/User.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java similarity index 94% rename from java-streams/src/main/java/com/baeldung/reduce/entities/User.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java index a17c6a02b6..6e0a529de6 100644 --- a/java-streams/src/main/java/com/baeldung/reduce/entities/User.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java @@ -1,25 +1,25 @@ -package com.baeldung.reduce.entities; - -public class User { - - private final String name; - private final int age; - - public User(String name, int age) { - this.name = name; - this.age = age; - } - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - @Override - public String toString() { - return "User{" + "name=" + name + ", age=" + age + '}'; - } -} +package com.baeldung.reduce.entities; + +public class User { + + private final String name; + private final int age; + + public User(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "User{" + "name=" + name + ", age=" + age + '}'; + } +} diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java similarity index 97% rename from java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java index a7a4b8df29..38d5b50120 100644 --- a/java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java @@ -1,52 +1,52 @@ -package com.baeldung.reduce.utilities; - -import java.util.List; -import java.util.function.BiFunction; -import java.util.logging.Level; -import java.util.logging.Logger; - -public abstract class NumberUtils { - - private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); - - public static int divideListElements(List values, Integer divider) { - return values.stream() - .reduce(0, (a, b) -> { - try { - return a / divider + b / divider; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return 0; - }); - } - - public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { - return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); - } - - public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { - BiFunction division = (a, b) -> a / b; - return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); - } - - private static int divide(int value, int factor) { - int result = 0; - try { - result = value / factor; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return result; - } - - private static int applyFunction(BiFunction function, int a, int b) { - try { - return function.apply(a, b); - } - catch(Exception e) { - LOGGER.log(Level.INFO, "Exception thrown!"); - } - return 0; - } -} +package com.baeldung.reduce.utilities; + +import java.util.List; +import java.util.function.BiFunction; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class NumberUtils { + + private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); + + public static int divideListElements(List values, Integer divider) { + return values.stream() + .reduce(0, (a, b) -> { + try { + return a / divider + b / divider; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return 0; + }); + } + + public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { + return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); + } + + public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { + BiFunction division = (a, b) -> a / b; + return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); + } + + private static int divide(int value, int factor) { + int result = 0; + try { + result = value / factor; + } catch (ArithmeticException e) { + LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); + } + return result; + } + + private static int applyFunction(BiFunction function, int a, int b) { + try { + return function.apply(a, b); + } + catch(Exception e) { + LOGGER.log(Level.INFO, "Exception thrown!"); + } + return 0; + } +} diff --git a/java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/streams/MyImmutableListCollector.java similarity index 93% rename from java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java rename to core-java-modules/core-java-streams-2/src/main/java/com/baeldung/streams/MyImmutableListCollector.java index cf6b3601c3..6d515bfb46 100644 --- a/java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java +++ b/core-java-modules/core-java-streams-2/src/main/java/com/baeldung/streams/MyImmutableListCollector.java @@ -1,4 +1,4 @@ -package com.baeldung.stream.mycollectors; +package com.baeldung.streams; import java.util.ArrayList; import java.util.Collections; diff --git a/core-java-modules/core-java-datetime/src/main/resources/logback.xml b/core-java-modules/core-java-streams-2/src/main/resources/logback.xml similarity index 100% rename from core-java-modules/core-java-datetime/src/main/resources/logback.xml rename to core-java-modules/core-java-streams-2/src/main/resources/logback.xml diff --git a/java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java similarity index 100% rename from java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java diff --git a/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/reduce/StreamReduceUnitTest.java similarity index 95% rename from java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/reduce/StreamReduceUnitTest.java index 564d614017..21eedf953e 100644 --- a/java-streams-2/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/reduce/StreamReduceUnitTest.java @@ -1,79 +1,80 @@ -package com.baeldung.reduce.tests; - -import com.baeldung.reduce.entities.User; -import com.baeldung.reduce.utilities.NumberUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class StreamReduceUnitTest { - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, Integer::sum); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (partialString, element) -> partialString + element); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); - assertThat(result).isEqualTo("ABCDE"); - } - - @Test - public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - assertThat(result).isEqualTo(65); - } - - @Test - public void givenStringList_whenReduceWithParallelStream_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.parallelStream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); - } -} +package com.baeldung.reduce; + +import com.baeldung.reduce.entities.User; +import com.baeldung.reduce.utilities.NumberUtils; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StreamReduceUnitTest { + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + int result = numbers.stream().reduce(0, Integer::sum); + assertThat(result).isEqualTo(21); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString + element); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); + assertThat(result).isEqualTo("ABCDE"); + } + + @Test + public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { + List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); + int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); + assertThat(result).isEqualTo(65); + } + + @Test + public void givenStringList_whenReduceWithParallelStream_thenCorrect() { + List letters = Arrays.asList("a", "b", "c", "d", "e"); + String result = letters.parallelStream().reduce("", String::concat); + assertThat(result).isEqualTo("abcde"); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); + } + + @Test + public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { + List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); + assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); + } +} diff --git a/java-streams/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Detail.java similarity index 85% rename from java-streams/src/main/java/com/baeldung/java_8_features/Detail.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Detail.java index 811937dba7..d2f5774b24 100644 --- a/java-streams/src/main/java/com/baeldung/java_8_features/Detail.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Detail.java @@ -1,4 +1,4 @@ -package com.baeldung.java_8_features; +package com.baeldung.streams; import java.util.Arrays; import java.util.List; diff --git a/java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8FindAnyFindFirstUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8FindAnyFindFirstUnitTest.java index 5f52fe375e..934d7b3542 100644 --- a/java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8FindAnyFindFirstUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8.streams; +package com.baeldung.streams; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java similarity index 99% rename from java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java index 75cfbc049f..c4e1f2b3cb 100644 --- a/java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamApiUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.java8.streams; +package com.baeldung.streams; -import com.baeldung.stream.Product; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; diff --git a/java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamsUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamsUnitTest.java index e40f9f9506..f46fa79b08 100644 --- a/java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Java8StreamsUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.java8; +package com.baeldung.streams; -import com.baeldung.java_8_features.Detail; import org.junit.Before; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/PeekUnitTest.java similarity index 98% rename from java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/PeekUnitTest.java index a3a2816e9c..97af4149d3 100644 --- a/java-streams/src/test/java/com/baeldung/stream/PeekUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/PeekUnitTest.java @@ -1,13 +1,13 @@ -package com.baeldung.stream; +package com.baeldung.streams; -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.StringWriter; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; public class PeekUnitTest { diff --git a/java-streams/src/main/java/com/baeldung/stream/Product.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Product.java similarity index 96% rename from java-streams/src/main/java/com/baeldung/stream/Product.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Product.java index e99a969b81..7883f055a1 100644 --- a/java-streams/src/main/java/com/baeldung/stream/Product.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/Product.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.streams; import java.util.List; import java.util.stream.Stream; diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamAddUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamAddUnitTest.java index d0745b8bc9..1fada26de5 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamAddUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.streams; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamMapUnitTest.java similarity index 96% rename from java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamMapUnitTest.java index 5cb2a274d1..509a3a3569 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamMapUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamMapUnitTest.java @@ -1,16 +1,13 @@ -package com.baeldung.stream; +package com.baeldung.streams; import org.junit.Before; import org.junit.Test; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java similarity index 81% rename from java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java index bd540201d2..e5339d8327 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/StreamToImmutableUnitTest.java @@ -1,20 +1,12 @@ -package com.baeldung.stream; - -import static java.util.stream.Collectors.collectingAndThen; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toSet; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.IntStream; +package com.baeldung.streams; +import com.google.common.collect.ImmutableList; import org.junit.Test; -import com.baeldung.stream.mycollectors.MyImmutableListCollector; -import com.google.common.collect.ImmutableList; +import java.util.*; +import java.util.stream.IntStream; + +import static java.util.stream.Collectors.*; public class StreamToImmutableUnitTest { diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/removeitem/StreamOperateAndRemoveUnitTest.java similarity index 98% rename from java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java rename to core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/removeitem/StreamOperateAndRemoveUnitTest.java index c5aa9a1651..194d0bd4d6 100644 --- a/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java +++ b/core-java-modules/core-java-streams-2/src/test/java/com/baeldung/streams/removeitem/StreamOperateAndRemoveUnitTest.java @@ -1,9 +1,4 @@ -package com.baeldung.stream; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Predicate; -import java.util.stream.Collectors; +package com.baeldung.streams.removeitem; import org.junit.Assert; import org.junit.Before; @@ -11,6 +6,11 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + public class StreamOperateAndRemoveUnitTest { private List itemList; diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md new file mode 100644 index 0000000000..4b2c9ed94c --- /dev/null +++ b/core-java-modules/core-java-streams-3/README.md @@ -0,0 +1,11 @@ +## Core Java streams + +This module contains articles about the Stream API in Java. + +### Relevant Articles: +- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap) +- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) +- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) +- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) +- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) +- More articles: [[<-- prev>]](/../core-java-streams-2) \ No newline at end of file diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml new file mode 100644 index 0000000000..b5b21a4368 --- /dev/null +++ b/core-java-modules/core-java-streams-3/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + core-java-streams-3 + 0.1.0-SNAPSHOT + core-java-streams-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-streams-3 + + + src/main/resources + true + + + + + + + 3.6.1 + + 2.22.1 + + diff --git a/core-java-modules/core-java-streams/src/main/java/com/baeldung/forEach/ReverseList.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/forEach/ReverseList.java similarity index 98% rename from core-java-modules/core-java-streams/src/main/java/com/baeldung/forEach/ReverseList.java rename to core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/forEach/ReverseList.java index b2ce77a9f6..c4128d9b72 100644 --- a/core-java-modules/core-java-streams/src/main/java/com/baeldung/forEach/ReverseList.java +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/forEach/ReverseList.java @@ -1,4 +1,4 @@ -package com.baeldung.forEach; +package com.baeldung.streams.forEach; import java.util.ArrayList; import java.util.Arrays; diff --git a/java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/primitivestreams/PrimitiveStreams.java similarity index 90% rename from java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java rename to core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/primitivestreams/PrimitiveStreams.java index b0afb65a35..fb2001f10f 100644 --- a/java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/primitivestreams/PrimitiveStreams.java @@ -1,4 +1,4 @@ -package com.baeldung.stream; +package com.baeldung.streams.primitivestreams; import java.util.Arrays; import java.util.stream.IntStream; diff --git a/java-dates/src/main/resources/logback.xml b/core-java-modules/core-java-streams-3/src/main/resources/logback.xml similarity index 100% rename from java-dates/src/main/resources/logback.xml rename to core-java-modules/core-java-streams-3/src/main/resources/logback.xml diff --git a/core-java-modules/core-java-streams/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java similarity index 99% rename from core-java-modules/core-java-streams/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java index e742635758..6afc9f4182 100644 --- a/core-java-modules/core-java-streams/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/collectors/Java8CollectorsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.collectors; +package com.baeldung.streams.collectors; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; diff --git a/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/conditional/StreamForEachIfElseUnitTest.java similarity index 96% rename from core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/conditional/StreamForEachIfElseUnitTest.java index b5d26eb6a8..a49a092864 100644 --- a/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/conditional/StreamForEachIfElseUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.stream.conditional; +package com.baeldung.streams.conditional; import java.util.Arrays; import java.util.List; diff --git a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/primitivestreams/PrimitiveStreamsUnitTest.java similarity index 98% rename from java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/primitivestreams/PrimitiveStreamsUnitTest.java index 67954f0bba..18966425e4 100644 --- a/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/primitivestreams/PrimitiveStreamsUnitTest.java @@ -1,14 +1,14 @@ -package com.baeldung.stream; +package com.baeldung.streams.primitivestreams; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class PrimitiveStreamsUnitTest { diff --git a/java-dates/.gitignore b/core-java-modules/core-java-streams/.gitignore similarity index 100% rename from java-dates/.gitignore rename to core-java-modules/core-java-streams/.gitignore diff --git a/core-java-modules/core-java-streams/README.md b/core-java-modules/core-java-streams/README.md index e97641c221..e556c231fe 100644 --- a/core-java-modules/core-java-streams/README.md +++ b/core-java-modules/core-java-streams/README.md @@ -1,9 +1,16 @@ -========= +## Core Java streams -## Core Java 8 Cookbooks and Examples +This module contains articles about the Stream API in Java. ### Relevant Articles: -- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap) -- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) -- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) -- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) \ No newline at end of file +- [Java 8 and Infinite Streams](https://www.baeldung.com/java-inifinite-streams) +- [How to Get the Last Element of a Stream in Java?](https://www.baeldung.com/java-stream-last-element) +- [“Stream has already been operated upon or closed” Exception in Java](https://www.baeldung.com/java-stream-operated-upon-or-closed-exception) +- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream) +- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices) +- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) +- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) +- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) +- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) +- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum) +- More articles: [[next -->]](/../core-java-streams-2) \ No newline at end of file diff --git a/core-java-modules/core-java-streams/pom.xml b/core-java-modules/core-java-streams/pom.xml index 96d97f3759..9b68c8dded 100644 --- a/core-java-modules/core-java-streams/pom.xml +++ b/core-java-modules/core-java-streams/pom.xml @@ -14,6 +14,34 @@ + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + provided + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + org.assertj @@ -21,6 +49,36 @@ ${assertj.version} test + + com.codepoetics + protonpack + ${protonpack.version} + + + io.vavr + vavr + ${vavr.version} + + + one.util + streamex + ${streamex.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.aspectj + aspectjweaver + ${asspectj.version} + + + pl.touk + throwing-function + ${throwing-function.version} + @@ -31,10 +89,33 @@ true + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + -parameters + + + + + 0.9.0 + 1.15 + 0.6.5 + 2.10 + 1.3 - 3.6.1 + 3.11.1 + 1.8.9 + 3.1 + 1.8 + 1.8 diff --git a/java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java diff --git a/java-streams/src/main/java/com/baeldung/stream/StreamApi.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamApi.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/StreamApi.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamApi.java diff --git a/java-streams/src/main/java/com/baeldung/stream/StreamIndices.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamIndices.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/StreamIndices.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/StreamIndices.java diff --git a/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/filter/Customer.java similarity index 100% rename from java-streams/src/main/java/com/baeldung/stream/filter/Customer.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/filter/Customer.java diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java similarity index 94% rename from java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java index 3170b1fb31..c44aaf8005 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/ArithmeticUtils.java @@ -1,8 +1,8 @@ -package com.baeldung.stream.sum; - -public class ArithmeticUtils { - - public static int add(int a, int b) { - return a + b; - } -} +package com.baeldung.stream.sum; + +public class ArithmeticUtils { + + public static int add(int a, int b) { + return a + b; + } +} diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/Item.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/Item.java similarity index 94% rename from java-streams/src/main/java/com/baeldung/stream/sum/Item.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/Item.java index 2f162d6eda..28a1737db8 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/Item.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/Item.java @@ -1,31 +1,31 @@ -package com.baeldung.stream.sum; - -public class Item { - - private int id; - private Integer price; - - public Item(int id, Integer price) { - super(); - this.id = id; - this.price = price; - } - - // Standard getters and setters - public long getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public Integer getPrice() { - return price; - } - - public void setPrice(Integer price) { - this.price = price; - } - -} +package com.baeldung.stream.sum; + +public class Item { + + private int id; + private Integer price; + + public Item(int id, Integer price) { + super(); + this.id = id; + this.price = price; + } + + // Standard getters and setters + public long getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Integer getPrice() { + return price; + } + + public void setPrice(Integer price) { + this.price = price; + } + +} diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java similarity index 96% rename from java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java index 2f63cf8629..ea6459d360 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculator.java @@ -1,59 +1,59 @@ -package com.baeldung.stream.sum; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -public class StreamSumCalculator { - - public static Integer getSumUsingCustomizedAccumulator(List integers) { - return integers.stream() - .reduce(0, ArithmeticUtils::add); - - } - - public static Integer getSumUsingJavaAccumulator(List integers) { - return integers.stream() - .reduce(0, Integer::sum); - - } - - public static Integer getSumUsingReduce(List integers) { - return integers.stream() - .reduce(0, (a, b) -> a + b); - - } - - public static Integer getSumUsingCollect(List integers) { - - return integers.stream() - .collect(Collectors.summingInt(Integer::intValue)); - - } - - public static Integer getSumUsingSum(List integers) { - - return integers.stream() - .mapToInt(Integer::intValue) - .sum(); - } - - public static Integer getSumOfMapValues(Map map) { - - return map.values() - .stream() - .mapToInt(Integer::valueOf) - .sum(); - } - - public static Integer getSumIntegersFromString(String str) { - - Integer sum = Arrays.stream(str.split(" ")) - .filter((s) -> s.matches("\\d+")) - .mapToInt(Integer::valueOf) - .sum(); - - return sum; - } -} +package com.baeldung.stream.sum; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class StreamSumCalculator { + + public static Integer getSumUsingCustomizedAccumulator(List integers) { + return integers.stream() + .reduce(0, ArithmeticUtils::add); + + } + + public static Integer getSumUsingJavaAccumulator(List integers) { + return integers.stream() + .reduce(0, Integer::sum); + + } + + public static Integer getSumUsingReduce(List integers) { + return integers.stream() + .reduce(0, (a, b) -> a + b); + + } + + public static Integer getSumUsingCollect(List integers) { + + return integers.stream() + .collect(Collectors.summingInt(Integer::intValue)); + + } + + public static Integer getSumUsingSum(List integers) { + + return integers.stream() + .mapToInt(Integer::intValue) + .sum(); + } + + public static Integer getSumOfMapValues(Map map) { + + return map.values() + .stream() + .mapToInt(Integer::valueOf) + .sum(); + } + + public static Integer getSumIntegersFromString(String str) { + + Integer sum = Arrays.stream(str.split(" ")) + .filter((s) -> s.matches("\\d+")) + .mapToInt(Integer::valueOf) + .sum(); + + return sum; + } +} diff --git a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java similarity index 96% rename from java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java rename to core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java index b83616928e..8a162429d2 100644 --- a/java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java +++ b/core-java-modules/core-java-streams/src/main/java/com/baeldung/stream/sum/StreamSumCalculatorWithObject.java @@ -1,38 +1,38 @@ -package com.baeldung.stream.sum; - -import java.util.List; -import java.util.stream.Collectors; - -public class StreamSumCalculatorWithObject { - - public static Integer getSumUsingCustomizedAccumulator(List items) { - return items.stream() - .map(x -> x.getPrice()) - .reduce(0, ArithmeticUtils::add); - } - - public static Integer getSumUsingJavaAccumulator(List items) { - return items.stream() - .map(x -> x.getPrice()) - .reduce(0, Integer::sum); - } - - public static Integer getSumUsingReduce(List items) { - return items.stream() - .map(item -> item.getPrice()) - .reduce(0, (a, b) -> a + b); - } - - public static Integer getSumUsingCollect(List items) { - return items.stream() - .map(x -> x.getPrice()) - .collect(Collectors.summingInt(Integer::intValue)); - } - - public static Integer getSumUsingSum(List items) { - return items.stream() - .mapToInt(x -> x.getPrice()) - .sum(); - } - -} +package com.baeldung.stream.sum; + +import java.util.List; +import java.util.stream.Collectors; + +public class StreamSumCalculatorWithObject { + + public static Integer getSumUsingCustomizedAccumulator(List items) { + return items.stream() + .map(x -> x.getPrice()) + .reduce(0, ArithmeticUtils::add); + } + + public static Integer getSumUsingJavaAccumulator(List items) { + return items.stream() + .map(x -> x.getPrice()) + .reduce(0, Integer::sum); + } + + public static Integer getSumUsingReduce(List items) { + return items.stream() + .map(item -> item.getPrice()) + .reduce(0, (a, b) -> a + b); + } + + public static Integer getSumUsingCollect(List items) { + return items.stream() + .map(x -> x.getPrice()) + .collect(Collectors.summingInt(Integer::intValue)); + } + + public static Integer getSumUsingSum(List items) { + return items.stream() + .mapToInt(x -> x.getPrice()) + .sum(); + } + +} diff --git a/java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/conversion/IterableStreamConversionUnitTest.java similarity index 96% rename from java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/conversion/IterableStreamConversionUnitTest.java index 99e8088054..f65f91a768 100644 --- a/java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/conversion/IterableStreamConversionUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java.conversion; +package com.baeldung.conversion; import org.junit.Assert; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java index a496e18b2d..69edc4f535 100644 --- a/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java @@ -1,35 +1,35 @@ -package com.baeldung.stream; - -import static org.junit.Assert.fail; - -import java.util.Optional; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import org.junit.Test; - -public class SupplierStreamUnitTest { - - @Test(expected = IllegalStateException.class) - public void givenStream_whenStreamUsedTwice_thenThrowException() { - Stream stringStream = Stream.of("A", "B", "C", "D"); - Optional result1 = stringStream.findAny(); - System.out.println(result1.get()); - Optional result2 = stringStream.findFirst(); - System.out.println(result2.get()); - } - - @Test - public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() { - try { - Supplier> streamSupplier = () -> Stream.of("A", "B", "C", "D"); - Optional result1 = streamSupplier.get().findAny(); - System.out.println(result1.get()); - Optional result2 = streamSupplier.get().findFirst(); - System.out.println(result2.get()); - } catch (IllegalStateException e) { - fail(); - } - } - +package com.baeldung.stream; + +import static org.junit.Assert.fail; + +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import org.junit.Test; + +public class SupplierStreamUnitTest { + + @Test(expected = IllegalStateException.class) + public void givenStream_whenStreamUsedTwice_thenThrowException() { + Stream stringStream = Stream.of("A", "B", "C", "D"); + Optional result1 = stringStream.findAny(); + System.out.println(result1.get()); + Optional result2 = stringStream.findFirst(); + System.out.println(result2.get()); + } + + @Test + public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() { + try { + Supplier> streamSupplier = () -> Stream.of("A", "B", "C", "D"); + Optional result1 = streamSupplier.get().findAny(); + System.out.println(result1.get()); + Optional result2 = streamSupplier.get().findFirst(); + System.out.println(result2.get()); + } catch (IllegalStateException e) { + fail(); + } + } + } \ No newline at end of file diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamCountUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java diff --git a/java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java index 46e1af9a4a..f03703154a 100644 --- a/java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/stream/sum/StreamSumUnitTest.java @@ -1,136 +1,136 @@ -package com.baeldung.stream.sum; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.Test; - -public class StreamSumUnitTest { - - @Test - public void givenListOfIntegersWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingCustomizedAccumulator(integers); - assertEquals(15, sum.intValue()); - - } - - @Test - public void givenListOfIntegersWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingJavaAccumulator(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfIntegersWhenSummingUsingReduceThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingReduce(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfIntegersWhenSummingUsingCollectThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingCollect(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfIntegersWhenSummingUsingSumThenCorrectValueReturned() { - List integers = Arrays.asList(1, 2, 3, 4, 5); - Integer sum = StreamSumCalculator.getSumUsingSum(integers); - assertEquals(15, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingCustomizedAccumulator(items); - assertEquals(90, sum.intValue()); - - } - - @Test - public void givenListOfItemsWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingJavaAccumulator(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingReduceThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingReduce(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingCollectThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingCollect(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenListOfItemsWhenSummingUsingSumThenCorrectValueReturned() { - Item item1 = new Item(1, 10); - Item item2 = new Item(2, 15); - Item item3 = new Item(3, 25); - Item item4 = new Item(4, 40); - - List items = Arrays.asList(item1, item2, item3, item4); - - Integer sum = StreamSumCalculatorWithObject.getSumUsingSum(items); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenMapWhenSummingThenCorrectValueReturned() { - Map map = new HashMap(); - map.put(1, 10); - map.put(2, 15); - map.put(3, 25); - map.put(4, 40); - - Integer sum = StreamSumCalculator.getSumOfMapValues(map); - assertEquals(90, sum.intValue()); - } - - @Test - public void givenStringWhenSummingThenCorrectValueReturned() { - String string = "Item1 10 Item2 25 Item3 30 Item4 45"; - - Integer sum = StreamSumCalculator.getSumIntegersFromString(string); - assertEquals(110, sum.intValue()); - } - -} +package com.baeldung.stream.sum; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +public class StreamSumUnitTest { + + @Test + public void givenListOfIntegersWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingCustomizedAccumulator(integers); + assertEquals(15, sum.intValue()); + + } + + @Test + public void givenListOfIntegersWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingJavaAccumulator(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfIntegersWhenSummingUsingReduceThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingReduce(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfIntegersWhenSummingUsingCollectThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingCollect(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfIntegersWhenSummingUsingSumThenCorrectValueReturned() { + List integers = Arrays.asList(1, 2, 3, 4, 5); + Integer sum = StreamSumCalculator.getSumUsingSum(integers); + assertEquals(15, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingCustomizedAccumulator(items); + assertEquals(90, sum.intValue()); + + } + + @Test + public void givenListOfItemsWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingJavaAccumulator(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingReduceThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingReduce(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingCollectThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingCollect(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenListOfItemsWhenSummingUsingSumThenCorrectValueReturned() { + Item item1 = new Item(1, 10); + Item item2 = new Item(2, 15); + Item item3 = new Item(3, 25); + Item item4 = new Item(4, 40); + + List items = Arrays.asList(item1, item2, item3, item4); + + Integer sum = StreamSumCalculatorWithObject.getSumUsingSum(items); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenMapWhenSummingThenCorrectValueReturned() { + Map map = new HashMap(); + map.put(1, 10); + map.put(2, 15); + map.put(3, 25); + map.put(4, 40); + + Integer sum = StreamSumCalculator.getSumOfMapValues(map); + assertEquals(90, sum.intValue()); + } + + @Test + public void givenStringWhenSummingThenCorrectValueReturned() { + String string = "Item1 10 Item2 25 Item3 30 Item4 45"; + + Integer sum = StreamSumCalculator.getSumIntegersFromString(string); + assertEquals(110, sum.intValue()); + } + +} diff --git a/java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/BenchmarkManualTest.java diff --git a/java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java similarity index 100% rename from java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java rename to core-java-modules/core-java-streams/src/test/java/com/baeldung/streamordering/StreamsOrderingUnitTest.java diff --git a/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/java-strings-ops/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml similarity index 57% rename from java-strings-ops/pom.xml rename to core-java-modules/core-java-string-algorithms/pom.xml index b6a7ea2728..f1b7499b6d 100644 --- a/java-strings-ops/pom.xml +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -1,36 +1,33 @@ 4.0.0 - com.baeldung - java-strings-ops + core-java-string-algorithms 0.1.0-SNAPSHOT jar - java-strings-ops + core-java-string-algorithms com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java + + com.google.guava + guava + ${guava.version} + org.apache.commons commons-lang3 ${commons-lang3.version} - log4j - log4j - ${log4j.version} - - - - org.assertj - assertj-core - ${assertj.version} - test + org.ahocorasick + ahocorasick + ${ahocorasick.version} org.openjdk.jmh @@ -40,60 +37,37 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh-generator.version} + ${jmh-core.version} - com.google.guava - guava - ${guava.version} + com.vdurmont + emoji-java + ${emoji-java.version} - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter-api.version} + org.assertj + assertj-core + ${assertj.version} test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - java-strings-ops + core-java-string-algorithms src/main/resources true - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - 3.8.1 - - 3.6.1 27.0.1-jre - 5.3.1 + 0.4.0 + 3.6.1 + 4.0.0 diff --git a/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/matchwords/MatchWords.java similarity index 92% rename from java-strings-2/src/main/java/com/baeldung/string/MatchWords.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/matchwords/MatchWords.java index 0cad52c320..b5b7e92d8e 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/matchwords/MatchWords.java @@ -1,14 +1,12 @@ -package com.baeldung.string; +package com.baeldung.matchwords; import org.ahocorasick.trie.Emit; -import org.ahocorasick.trie.Token; import org.ahocorasick.trie.Trie; -import java.util.*; -import java.util.function.Function; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; public class MatchWords { diff --git a/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/palindrom/Palindrome.java similarity index 98% rename from java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/palindrom/Palindrome.java index 97d4d36d07..4a98e6583a 100644 --- a/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/palindrom/Palindrome.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.palindrom; import java.util.stream.IntStream; diff --git a/java-strings-2/src/main/java/com/baeldung/string/Pangram.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/pangram/Pangram.java similarity index 98% rename from java-strings-2/src/main/java/com/baeldung/string/Pangram.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/pangram/Pangram.java index c09b0c1d29..ca2a44280c 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/Pangram.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/pangram/Pangram.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.pangram; import java.util.Arrays; import java.util.Map; diff --git a/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/removeduplicates/RemoveDuplicateFromString.java similarity index 98% rename from java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/removeduplicates/RemoveDuplicateFromString.java index d8fd9c4b14..a000f4dbd6 100644 --- a/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/removeduplicates/RemoveDuplicateFromString.java @@ -1,4 +1,4 @@ -package com.baeldung.stringduplicates; +package com.baeldung.removeduplicates; import java.util.Arrays; import java.util.HashSet; diff --git a/java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/repetition/SubstringRepetition.java similarity index 94% rename from java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/repetition/SubstringRepetition.java index 466ce9146b..6715367a19 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/repetition/SubstringRepetition.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/repetition/SubstringRepetition.java @@ -1,4 +1,4 @@ -package com.baeldung.string.repetition; +package com.baeldung.repetition; public class SubstringRepetition { diff --git a/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java similarity index 97% rename from java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java index 1a58d09598..5236f14ccd 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java @@ -1,4 +1,4 @@ -package com.baeldung.string.reverse; +package com.baeldung.reverse; import org.apache.commons.lang3.StringUtils; diff --git a/java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/searching/WordIndexer.java similarity index 96% rename from java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/searching/WordIndexer.java index 1bcad6dd32..c7550f8e16 100644 --- a/java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/searching/WordIndexer.java @@ -1,4 +1,4 @@ -package com.baeldung.string.searching; +package com.baeldung.searching; import java.util.ArrayList; import java.util.List; diff --git a/java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/stopwords/RemovingStopwordsPerformanceComparison.java similarity index 82% rename from java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java rename to core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/stopwords/RemovingStopwordsPerformanceComparison.java index 5b455459cd..7df64de3f1 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/performance/RemovingStopwordsPerformanceComparison.java +++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/stopwords/RemovingStopwordsPerformanceComparison.java @@ -1,4 +1,6 @@ -package com.baeldung.string.performance; +package com.baeldung.stopwords; + +import org.openjdk.jmh.annotations.*; import java.io.IOException; import java.nio.file.Files; @@ -9,15 +11,6 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; - @Fork(value = 3, warmups = 1) @State(Scope.Benchmark) diff --git a/java-strings-2/src/main/resources/english_stopwords.txt b/core-java-modules/core-java-string-algorithms/src/main/resources/english_stopwords.txt similarity index 100% rename from java-strings-2/src/main/resources/english_stopwords.txt rename to core-java-modules/core-java-string-algorithms/src/main/resources/english_stopwords.txt diff --git a/java-strings-2/src/main/resources/shakespeare-hamlet.txt b/core-java-modules/core-java-string-algorithms/src/main/resources/shakespeare-hamlet.txt similarity index 100% rename from java-strings-2/src/main/resources/shakespeare-hamlet.txt rename to core-java-modules/core-java-string-algorithms/src/main/resources/shakespeare-hamlet.txt diff --git a/java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/countingchars/CountCharsExampleUnitTest.java similarity index 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/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringUnitTest.java similarity index 96% rename from java-strings/src/test/java/com/baeldung/string/StringUnitTest.java rename to core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringUnitTest.java index 0d4fd6eff9..5c1fe2fbda 100644 --- a/java-strings/src/test/java/com/baeldung/string/StringUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/stringapi/StringUnitTest.java @@ -1,16 +1,13 @@ -package com.baeldung.string; +package com.baeldung.stringapi; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.Test; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.IllegalFormatException; import java.util.regex.PatternSyntaxException; -import org.junit.Test; +import static org.junit.Assert.*; public class StringUnitTest { diff --git a/core-java-modules/core-java-string-conversions-2/README.md b/core-java-modules/core-java-string-conversions-2/README.md index b4da1b8bad..afdd7e5760 100644 --- a/core-java-modules/core-java-string-conversions-2/README.md +++ b/core-java-modules/core-java-string-conversions-2/README.md @@ -5,5 +5,5 @@ This module contains articles about string conversions from/to another type. ### Relevant Articles: - [Java String Conversions](https://www.baeldung.com/java-string-conversions) - [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Convert Char Array to String](https://www.baeldung.com/java-char-array-to-string) +- [Convert Character Array to String in Java](https://www.baeldung.com/java-char-array-to-string) - More articles: [[<-- prev]](/core-java-string-conversions) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md new file mode 100644 index 0000000000..50f40ac2af --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -0,0 +1,11 @@ +## Java String Operations + +This module contains articles about string operations. + +### Relevant Articles: +- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) +- [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) +- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case) +- [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase) +- More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml new file mode 100644 index 0000000000..95aeec8fcb --- /dev/null +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -0,0 +1,81 @@ + + 4.0.0 + core-java-string-operations-2 + 0.1.0-SNAPSHOT + jar + core-java-string-operations-2 + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + javax.validation + validation-api + ${validation-api.version} + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish.web + javax.el + ${javax.el.version} + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-string-operations-2 + + + src/main/resources + true + + + + + + 3.6.1 + 2.0.0.Final + 3.8.1 + 27.0.1-jre + 6.0.2.Final + 3.0.0 + 2.2.6 + + + diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/EmptyStringCheck.java similarity index 75% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/EmptyStringCheck.java index 6d3234a4ec..85689eff99 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/EmptyStringCheck.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; class EmptyStringCheck { diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/Java5EmptyStringCheck.java similarity index 76% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/Java5EmptyStringCheck.java index 096b83acea..0c7997c075 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/Java5EmptyStringCheck.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; class Java5EmptyStringCheck { diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/PlainJavaBlankStringCheck.java similarity index 77% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/PlainJavaBlankStringCheck.java index 26e281c9b7..315ce4613a 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/PlainJavaBlankStringCheck.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; class PlainJavaBlankStringCheck { diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java similarity index 87% rename from java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java rename to core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java index 8c484efb43..058d53ba82 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java +++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/emptystrings/SomeClassWithValidations.java @@ -1,4 +1,4 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; import javax.validation.constraints.Pattern; diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToLowerCaseUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToLowerCaseUnitTest.java index c395b61068..4826ba2ef7 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToLowerCaseUnitTest.java @@ -1,29 +1,29 @@ -package com.baeldung.string.changecase; - -import static org.junit.Assert.assertEquals; - -import java.util.Locale; - -import org.junit.Test; - -public class ToLowerCaseUnitTest { - - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignUppercase = "\u0049"; - - @Test - public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { - assertEquals("john doe", name.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { - assertEquals("\u0069", foreignUppercase.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { - assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); - } -} +package com.baeldung.changecase; + +import org.junit.Test; + +import java.util.Locale; + +import static org.junit.Assert.assertEquals; + +public class ToLowerCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0049"; + + @Test + public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { + assertEquals("john doe", name.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { + assertEquals("\u0069", foreignUppercase.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { + assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToUpperCaseUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToUpperCaseUnitTest.java index 1807f854b2..ab740f19b1 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/changecase/ToUpperCaseUnitTest.java @@ -1,29 +1,29 @@ -package com.baeldung.string.changecase; - -import static org.junit.Assert.assertEquals; - -import java.util.Locale; - -import org.junit.Test; - -public class ToUpperCaseUnitTest { - - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignLowercase = "\u0069"; - - @Test - public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { - assertEquals("JOHN DOE", name.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { - assertEquals("\u0049", foreignLowercase.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { - assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH)); - } -} +package com.baeldung.changecase; + +import org.junit.Test; + +import java.util.Locale; + +import static org.junit.Assert.assertEquals; + +public class ToUpperCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignLowercase = "\u0069"; + + @Test + public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { + assertEquals("JOHN DOE", name.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { + assertEquals("\u0049", foreignLowercase.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { + assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java similarity index 96% rename from java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java index 96b1d681dd..d772c38341 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java @@ -1,21 +1,17 @@ -package com.baeldung.string.emptystrings; +package com.baeldung.emptystrings; -import static org.hamcrest.Matchers.iterableWithSize; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Set; +import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; +import java.util.Set; -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; - -import com.google.common.base.Strings; +import static org.hamcrest.Matchers.iterableWithSize; +import static org.junit.Assert.*; public class EmptyStringsUnitTest { diff --git a/java-strings-3/src/test/java/com/baeldung/string/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java similarity index 94% rename from java-strings-3/src/test/java/com/baeldung/string/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java index 5aab63db94..14fbf20c1d 100644 --- a/java-strings-3/src/test/java/com/baeldung/string/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/equalsIgnoreCase/StringEqualsIgnoreCaseUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string.equalsIgnoreCase; +package com.baeldung.equalsIgnoreCase; import org.apache.commons.lang3.StringUtils; import org.junit.Test; diff --git a/java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java index 50d9a2b058..02beaa690a 100644 --- a/java-strings-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/initialization/StringInitializationUnitTest.java @@ -1,11 +1,9 @@ package com.baeldung.initialization; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; - import org.junit.Test; +import static org.junit.Assert.*; + public class StringInitializationUnitTest { private String fieldString; diff --git a/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/stringconcatenation/StringConcatenationUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java rename to core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/stringconcatenation/StringConcatenationUnitTest.java index c25d4ce8f9..9a444e8229 100644 --- a/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/stringconcatenation/StringConcatenationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.stringconcatenation; import org.junit.Test; diff --git a/core-java-modules/core-java-string-operations/README.md b/core-java-modules/core-java-string-operations/README.md new file mode 100644 index 0000000000..18a2649a6a --- /dev/null +++ b/core-java-modules/core-java-string-operations/README.md @@ -0,0 +1,16 @@ +## Java String Operations + +This module contains articles about string operations. + +### Relevant Articles: +- [Comparing Strings in Java](https://www.baeldung.com/java-compare-strings) +- [Check If a String Is Numeric in Java](https://www.baeldung.com/java-check-string-number) +- [Get Substring from String in Java](https://www.baeldung.com/java-substring) +- [Split a String in Java](https://www.baeldung.com/java-split-string) +- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Java toString() Method](https://www.baeldung.com/java-tostring) +- [String Operations with Java Streams](https://www.baeldung.com/java-stream-operations-on-strings) +- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) +- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) +- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) +- More articles: [[next -->]](../core-java-string-operations-2) diff --git a/java-strings/pom.xml b/core-java-modules/core-java-string-operations/pom.xml old mode 100755 new mode 100644 similarity index 51% rename from java-strings/pom.xml rename to core-java-modules/core-java-string-operations/pom.xml index 42a57bfb42..fdddd99433 --- a/java-strings/pom.xml +++ b/core-java-modules/core-java-string-operations/pom.xml @@ -1,117 +1,66 @@ 4.0.0 - com.baeldung - java-strings + core-java-string-operations 0.1.0-SNAPSHOT jar - java-strings + core-java-string-operations com.baeldung parent-java 0.0.1-SNAPSHOT - ../parent-java + ../../parent-java - - commons-io - commons-io - ${commons-io.version} - org.apache.commons commons-lang3 ${commons-lang3.version} - - log4j - log4j - ${log4j.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - - org.assertj - assertj-core - ${assertj.version} - test - org.openjdk.jmh jmh-core ${jmh-core.version} + + log4j + log4j + ${log4j.version} + org.openjdk.jmh jmh-generator-annprocess ${jmh-generator.version} - com.ibm.icu - icu4j - ${icu4j.version} + commons-codec + commons-codec + ${commons-codec.version} - com.google.guava - guava - ${guava.version} - - - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter-api.version} + org.assertj + assertj-core + ${assertj.version} test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - java-strings + core-java-string-operations src/main/resources true - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - 3.8.1 - 1.10 - 3.6.1 - 61.1 - 27.0.1-jre - 5.3.1 - 1.4 + 1.10 diff --git a/java-strings/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-strings/README.md b/core-java-modules/core-java-strings/README.md new file mode 100644 index 0000000000..4a418db29f --- /dev/null +++ b/core-java-modules/core-java-strings/README.md @@ -0,0 +1,14 @@ +## Java Strings + +This module contains articles about strings in Java. + +### Relevant Articles: +- [Use char[] Array over a String for Manipulating Passwords in Java?](https://www.baeldung.com/java-storing-passwords) +- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string) +- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) +- [String Performance Hints](https://www.baeldung.com/java-string-performance) +- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) +- [Java – Generate Random String](https://www.baeldung.com/java-random-string) +- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) +- [Java Multi-line String](https://www.baeldung.com/java-multiline-string) +- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) diff --git a/core-java-modules/core-java-strings/pom.xml b/core-java-modules/core-java-strings/pom.xml new file mode 100644 index 0000000000..6a80886549 --- /dev/null +++ b/core-java-modules/core-java-strings/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + core-java-strings + 0.1.0-SNAPSHOT + jar + core-java-strings + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + com.ibm.icu + icu4j + ${icu4j.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + core-java-strings + + + src/main/resources + true + + + + + + 3.6.1 + 61.1 + + + diff --git a/java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java similarity index 97% rename from java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java index cb24511f72..eae75eaa2b 100644 --- a/java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/java9/compactstring/CompactStringDemo.java @@ -1,9 +1,10 @@ package com.baeldung.java9.compactstring; import java.util.List; -import static java.util.stream.Collectors.toList; import java.util.stream.IntStream; +import static java.util.stream.Collectors.toList; + public class CompactStringDemo { public static void main(String[] args) { @@ -11,14 +12,14 @@ public class CompactStringDemo { List strings = IntStream.rangeClosed(1, 10_000_000) .mapToObj(Integer::toString).collect(toList()); long totalTime = System.currentTimeMillis() - startTime; - System.out.println("Generated " + strings.size() + " strings in " + System.out.println("Generated " + strings.size() + " strings in " + totalTime + " ms."); startTime = System.currentTimeMillis(); String appended = (String) strings.stream().limit(100_000) .reduce("", (left, right) -> left.toString() + right.toString()); totalTime = System.currentTimeMillis() - startTime; - System.out.println("Created string of length " + appended.length() + System.out.println("Created string of length " + appended.length() + " in " + totalTime + " ms."); } } diff --git a/java-strings-2/src/main/java/com/baeldung/localization/App.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/App.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/App.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/App.java diff --git a/java-strings-2/src/main/java/com/baeldung/localization/ICUFormat.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/ICUFormat.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/ICUFormat.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/ICUFormat.java index f7bc357933..c82af30c87 100644 --- a/java-strings-2/src/main/java/com/baeldung/localization/ICUFormat.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/ICUFormat.java @@ -1,11 +1,11 @@ package com.baeldung.localization; +import com.ibm.icu.text.MessageFormat; + import java.util.List; import java.util.Locale; import java.util.ResourceBundle; -import com.ibm.icu.text.MessageFormat; - public class ICUFormat { public static String getLabel(Locale locale, Object[] data) { diff --git a/java-strings-2/src/main/java/com/baeldung/localization/JavaSEFormat.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/JavaSEFormat.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/JavaSEFormat.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/JavaSEFormat.java diff --git a/java-strings-2/src/main/java/com/baeldung/localization/Localization.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/Localization.java similarity index 100% rename from java-strings-2/src/main/java/com/baeldung/localization/Localization.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/localization/Localization.java diff --git a/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/multiline/MultiLineString.java similarity index 98% rename from java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/multiline/MultiLineString.java index 1bde2dcb63..987bc751cd 100644 --- a/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/multiline/MultiLineString.java @@ -1,4 +1,7 @@ -package com.baeldung.string.multiline; +package com.baeldung.multiline; + +import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; import java.io.IOException; import java.io.PrintWriter; @@ -6,9 +9,6 @@ import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Paths; -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableList; - public class MultiLineString { String newLine = System.getProperty("line.separator"); diff --git a/java-strings/src/main/java/com/baeldung/string/StringPerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringperformance/StringPerformance.java similarity index 99% rename from java-strings/src/main/java/com/baeldung/string/StringPerformance.java rename to core-java-modules/core-java-strings/src/main/java/com/baeldung/stringperformance/StringPerformance.java index 3b0c32991c..8e9d3afdde 100644 --- a/java-strings/src/main/java/com/baeldung/string/StringPerformance.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringperformance/StringPerformance.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.stringperformance; import com.google.common.base.Splitter; import org.apache.commons.lang3.StringUtils; diff --git a/java-strings-2/src/main/resources/formats_en.properties b/core-java-modules/core-java-strings/src/main/resources/formats_en.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_en.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_en.properties diff --git a/java-strings-2/src/main/resources/formats_fr.properties b/core-java-modules/core-java-strings/src/main/resources/formats_fr.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_fr.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_fr.properties diff --git a/java-strings-2/src/main/resources/formats_it.properties b/core-java-modules/core-java-strings/src/main/resources/formats_it.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_it.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_it.properties diff --git a/java-strings-2/src/main/resources/formats_pl.properties b/core-java-modules/core-java-strings/src/main/resources/formats_pl.properties similarity index 100% rename from java-strings-2/src/main/resources/formats_pl.properties rename to core-java-modules/core-java-strings/src/main/resources/formats_pl.properties diff --git a/java-streams/src/main/resources/logback.xml b/core-java-modules/core-java-strings/src/main/resources/logback.xml similarity index 100% rename from java-streams/src/main/resources/logback.xml rename to core-java-modules/core-java-strings/src/main/resources/logback.xml diff --git a/java-strings-2/src/main/resources/messages_en.properties b/core-java-modules/core-java-strings/src/main/resources/messages_en.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_en.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_en.properties diff --git a/java-strings-2/src/main/resources/messages_fr.properties b/core-java-modules/core-java-strings/src/main/resources/messages_fr.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_fr.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_fr.properties diff --git a/java-strings-2/src/main/resources/messages_it.properties b/core-java-modules/core-java-strings/src/main/resources/messages_it.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_it.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_it.properties diff --git a/java-strings-2/src/main/resources/messages_pl.properties b/core-java-modules/core-java-strings/src/main/resources/messages_pl.properties similarity index 100% rename from java-strings-2/src/main/resources/messages_pl.properties rename to core-java-modules/core-java-strings/src/main/resources/messages_pl.properties diff --git a/java-strings-2/src/main/resources/stephenking.txt b/core-java-modules/core-java-strings/src/main/resources/stephenking.txt similarity index 100% rename from java-strings-2/src/main/resources/stephenking.txt rename to core-java-modules/core-java-strings/src/main/resources/stephenking.txt diff --git a/java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/LocaleUnitTest.java similarity index 93% rename from java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/LocaleUnitTest.java index 1d221056fd..5655d2536d 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/LocaleUnitTest.java @@ -1,11 +1,12 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; + +import org.junit.Test; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Locale; -import static org.junit.Assert.assertEquals; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class LocaleUnitTest { @Test diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringAnagramUnitTest.java similarity index 94% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringAnagramUnitTest.java index aadfade737..8f3bacc267 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringAnagramUnitTest.java @@ -1,10 +1,10 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; import java.util.Arrays; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; public class StringAnagramUnitTest { public boolean isAnagram(String s1, String s2) { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringChangeCaseUnitTest.java similarity index 92% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringChangeCaseUnitTest.java index 2c7ec500fe..4c3815a2e4 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringChangeCaseUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringChangeCaseUnitTest { @Test public void givenString_whenChangingToUppercase_thenCaseChanged() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringCountOccurrencesUnitTest.java similarity index 94% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringCountOccurrencesUnitTest.java index 6c17643ac8..cb92c06d32 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringCountOccurrencesUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringCountOccurrencesUnitTest { public int countOccurrences(String s, char c) { int count = 0; diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringFormatUnitTest.java similarity index 90% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringFormatUnitTest.java index 787017791c..8492db0dc0 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringFormatUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringFormatUnitTest { @Test public void givenString_whenUsingStringFormat_thenStringFormatted() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringInternUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringInternUnitTest.java index c5bffb7573..3092a72399 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringInternUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.assertj.core.api.Assertions.assertThat; +package com.baeldung.interview; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class StringInternUnitTest { @Test public void whenCallingStringIntern_thenStringsInterned() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringJoinerUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringJoinerUnitTest.java index d44c7478e4..b5556f588c 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringJoinerUnitTest.java @@ -1,10 +1,11 @@ -package com.baeldung.string.interview; - -import java.util.StringJoiner; -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import java.util.StringJoiner; + +import static org.junit.Assert.assertEquals; + public class StringJoinerUnitTest { @Test public void whenUsingStringJoiner_thenStringsJoined() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringPalindromeUnitTest.java similarity index 95% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringPalindromeUnitTest.java index 79ed14cd99..760939932a 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringPalindromeUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.assertj.core.api.Assertions.assertThat; +package com.baeldung.interview; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class StringPalindromeUnitTest { public boolean isPalindrome(String text) { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringReverseUnitTest.java similarity index 88% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringReverseUnitTest.java index bb9b45dc97..484a6d0d68 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringReverseUnitTest.java @@ -1,9 +1,9 @@ -package com.baeldung.string.interview; - -import static org.junit.Assert.assertEquals; +package com.baeldung.interview; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class StringReverseUnitTest { @Test public void whenUsingInbuildMethods_thenStringReversed() { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringSplitUnitTest.java similarity index 95% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringSplitUnitTest.java index e1cea62462..5aff593e3e 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringSplitUnitTest.java @@ -1,7 +1,8 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; import org.apache.commons.lang3.StringUtils; import org.junit.Test; + import static org.junit.Assert.assertArrayEquals; public class StringSplitUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToByteArrayUnitTest.java similarity index 95% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToByteArrayUnitTest.java index aee4eedcd6..90c5ca25c2 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToByteArrayUnitTest.java @@ -1,11 +1,11 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; -import static org.junit.Assert.assertArrayEquals; +import org.junit.Test; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; -import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; public class StringToByteArrayUnitTest { @Test diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToCharArrayUnitTest.java similarity index 91% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToCharArrayUnitTest.java index 1322d0fa82..5ebd7448f1 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToCharArrayUnitTest.java @@ -1,10 +1,10 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.Arrays; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class StringToCharArrayUnitTest { @Test diff --git a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToIntegerUnitTest.java similarity index 89% rename from java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToIntegerUnitTest.java index a905438a84..24a715dc75 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/interview/StringToIntegerUnitTest.java @@ -1,6 +1,7 @@ -package com.baeldung.string.interview; +package com.baeldung.interview; import org.junit.Test; + import static org.assertj.core.api.Assertions.assertThat; public class StringToIntegerUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java index 2c8f9b47f3..3c5c5fcb55 100644 --- a/java-strings-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java @@ -1,12 +1,10 @@ package com.baeldung.localization; -import static org.junit.Assert.assertEquals; - -import java.util.Locale; - import org.junit.Test; -import com.baeldung.localization.ICUFormat; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; public class ICUFormatUnitTest { diff --git a/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/multiline/MultiLineStringUnitTest.java similarity index 85% rename from java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/multiline/MultiLineStringUnitTest.java index 3ebee9b5d1..04d318c71b 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/multiline/MultiLineStringUnitTest.java @@ -1,11 +1,10 @@ -package com.baeldung.string.multiline; +package com.baeldung.multiline; import org.junit.Test; -import static org.junit.Assert.assertEquals; import java.io.IOException; -import com.baeldung.string.multiline.MultiLineString; +import static org.junit.Assert.assertEquals; public class MultiLineStringUnitTest { diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java new file mode 100644 index 0000000000..2806635d03 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/randomstrings/RandomStringsUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.randomstrings; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.charset.Charset; +import java.util.Random; + +public class RandomStringsUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(RandomStringsUnitTest.class); + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { + final byte[] array = new byte[7]; // length is bounded by 7 + new Random().nextBytes(array); + final String generatedString = new String(array, Charset.forName("UTF-8")); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { + final int leftLimit = 97; // letter 'a' + final int rightLimit = 122; // letter 'z' + final int targetStringLength = 10; + final Random random = new Random(); + final StringBuilder buffer = new StringBuilder(targetStringLength); + + for (int i = 0; i < targetStringLength; i++) { + final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); + buffer.append((char) randomLimitedInt); + } + final String generatedString = buffer.toString(); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { + final String generatedString = RandomStringUtils.random(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { + final String generatedString = RandomStringUtils.randomAlphabetic(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { + final String generatedString = RandomStringUtils.randomAlphanumeric(10); + + LOG.debug(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { + final int length = 10; + final boolean useLetters = true; + final boolean useNumbers = false; + final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); + + LOG.debug(generatedString); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringnotempty/StringNotEmptyUnitTest.java similarity index 81% rename from java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/stringnotempty/StringNotEmptyUnitTest.java index 17b13f89de..482105cc40 100644 --- a/java-strings/src/test/java/com/baeldung/string/StringEmptyUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringnotempty/StringNotEmptyUnitTest.java @@ -1,21 +1,16 @@ -package com.baeldung.string; - -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; -import static org.hamcrest.text.IsEmptyString.isEmptyString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +package com.baeldung.stringnotempty; +import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; import org.junit.Test; -import com.google.common.base.Strings; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; +import static org.hamcrest.text.IsEmptyString.isEmptyString; +import static org.junit.Assert.*; -public class StringEmptyUnitTest { +public class StringNotEmptyUnitTest { private String text = "baeldung"; diff --git a/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java similarity index 95% rename from java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java rename to core-java-modules/core-java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java index 4bbf63f87e..ca56d5aab5 100644 --- a/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java @@ -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/core-java-modules/core-java-time-measurements/README.md b/core-java-modules/core-java-time-measurements/README.md new file mode 100644 index 0000000000..1bd277b6b1 --- /dev/null +++ b/core-java-modules/core-java-time-measurements/README.md @@ -0,0 +1,8 @@ +## Java Time Measurements + +This module contains articles about the measurement of time in Java. + +### Relevant Articles: +- [Guide to the Java Clock Class](http://www.baeldung.com/java-clock) +- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) +- [Overriding System Time for Testing in Java](https://www.baeldung.com/java-override-system-time) diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml new file mode 100644 index 0000000000..0ff3787051 --- /dev/null +++ b/core-java-modules/core-java-time-measurements/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + com.baeldung.exception.numberformat + core-java-time-measurements + 0.0.1-SNAPSHOT + jar + core-java-time-measurements + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + joda-time + joda-time + ${joda.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + org.jmockit + jmockit + ${jmockit.version} + test + + + + + core-java-time-measurements + + + src/main/resources + true + + + + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar + + true + + + + + + + + 3.6.1 + 2.10 + + 3.6.1 + 1.8.9 + 2.0.0-RC.4 + 1.44 + + 2.22.1 + + diff --git a/java-strings-2/src/main/resources/logback.xml b/core-java-modules/core-java-time-measurements/src/main/resources/logback.xml similarity index 100% rename from java-strings-2/src/main/resources/logback.xml rename to core-java-modules/core-java-time-measurements/src/main/resources/logback.xml diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/java/clock/ClockUnitTest.java similarity index 100% rename from core-java-modules/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/java/clock/ClockUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java similarity index 100% rename from java-dates/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/ElapsedTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/InstantWithJMockUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/time/LocalDateTimeWithJMockUnitTest.java diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index 436a481803..c65428c6af 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -1,19 +1,13 @@ -========= - ## Core Java Cookbooks and Examples ### Relevant Articles: - [Java Timer](http://www.baeldung.com/java-timer-and-timertask) -- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java) -- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) - [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) - [Getting Started with Java Properties](http://www.baeldung.com/java-properties) -- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) - [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) -- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend) - [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null) - [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization) @@ -24,16 +18,12 @@ - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) -- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os) - [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java) - [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) -- [Class Loaders in Java](http://www.baeldung.com/java-classloaders) -- [Guide to the Java Clock Class](http://www.baeldung.com/java-clock) - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) - [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) - [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object) -- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation) - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) @@ -41,7 +31,7 @@ - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) - [Graphs in Java](https://www.baeldung.com/java-graphs) -- [Console I/O in Java](http://www.baeldung.com/java-console-input-output) +- [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output) - [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) - [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) - [Introduction to Basic Syntax in Java](https://www.baeldung.com/java-syntax) diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 392bcaa6dc..9d4bee081e 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -60,24 +60,6 @@ moneta ${javamoney.moneta.version} - - org.owasp.esapi - esapi - ${esapi.version} - - - - org.javassist - javassist - ${javaassist.version} - - - com.sun - tools - ${sun.tools.version} - system - ${java.home}/../lib/tools.jar - @@ -401,24 +383,18 @@ 0.4 1.8.7 - + 3.10.0 - + 1.1 - 2.1.0.1 - + 3.0.0-M1 3.0.2 1.4.4 3.1.1 2.0.3.RELEASE 1.6.0 - - - 3.21.0-GA - - 1.8.0 diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/README.md deleted file mode 100644 index 7b3b40c102..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/printscreen/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 68ece1c473..16ec19835a 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -19,6 +19,7 @@ core-java-lang-operators core-java-networking-2 core-java-security-manager + core-java-date-operations diff --git a/core-kotlin-2/README.md b/core-kotlin-2/README.md index ecf16c2c91..06dda396d9 100644 --- a/core-kotlin-2/README.md +++ b/core-kotlin-2/README.md @@ -12,4 +12,5 @@ This module contains articles about core Kotlin. - [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) - [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) - [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations) +- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) - More articles: [[<-- prev]](/core-kotlin) diff --git a/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 index 73b6b7e12a..7c9aeff07e 100644 --- a/gradle-5/README.md +++ b/gradle-5/README.md @@ -1,5 +1,3 @@ - ### Relevant Articles: - [Run a Java main Method Using Gradle](https://www.baeldung.com/gradle-run-java-main) - diff --git a/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 17c930cdd2..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 @@ -39,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/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java index 004314b0ed..c8910878a9 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/SpringAndHystrixIntegrationTest.java @@ -13,7 +13,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppConfig.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppConfig.class) public class SpringAndHystrixIntegrationTest { @Autowired diff --git a/jackson-simple/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/annotation/MyBean.java b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/MyBean.java index 5d4ce4202c..e4e78ce445 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/MyBean.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/MyBean.java @@ -1,8 +1,10 @@ package com.baeldung.jackson.annotation; +import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonSetter; @JsonInclude(Include.NON_NULL) @JsonPropertyOrder({ "name", "id" }) @@ -18,4 +20,14 @@ public class MyBean { this.id = id; this.name = name; } + + @JsonGetter("name") + public String getTheName() { + return name; + } + + @JsonSetter("name") + public void setTheName(String name) { + this.name = name; + } } diff --git a/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/java-collections-conversions-2/README.md b/java-collections-conversions-2/README.md new file mode 100644 index 0000000000..761e56253e --- /dev/null +++ b/java-collections-conversions-2/README.md @@ -0,0 +1,7 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about conversions among Collection types and arrays in Java. + +### Relevant Articles: +- [Array to String Conversions](https://www.baeldung.com/java-array-to-string) +- More articles: [[<-- prev]](../java-collections-conversions) \ No newline at end of file diff --git a/java-collections-conversions-2/pom.xml b/java-collections-conversions-2/pom.xml new file mode 100644 index 0000000000..72673527ac --- /dev/null +++ b/java-collections-conversions-2/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + java-collections-conversions-2 + 0.1.0-SNAPSHOT + java-collections-conversions-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + java-collections-conversions-2 + + + src/main/resources + true + + + + + + + diff --git a/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java similarity index 98% rename from java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java rename to java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java index b563475997..73cf9d6baa 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java +++ b/java-collections-conversions-2/src/test/java/com/baeldung/convertarraytostring/ArrayToStringUnitTest.java @@ -1,15 +1,14 @@ -package org.baeldung.convertarraytostring; +package com.baeldung.convertarraytostring; + +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; - -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; - import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index 6d4f6ddb3a..2d3aa41f2d 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -9,8 +9,8 @@ This module contains articles about conversions among Collection types and array - [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set) - [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string) - [How to Convert List to Map in Java](https://www.baeldung.com/java-list-to-map) -- [Array to String Conversions](https://www.baeldung.com/java-array-to-string) - [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) - [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap) - [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection) - [Converting Iterator to List](https://www.baeldung.com/java-convert-iterator-to-list) +- More articles: [[next -->]](../java-collections-conversions-2) \ No newline at end of file diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index 24d918d105..b5ab4f841a 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -32,6 +32,16 @@ + + java-collections-conversions-2 + + + src/main/resources + true + + + + 4.1 3.6.1 diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java similarity index 97% rename from java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java index 1de600aebf..ad2ab2a756 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java @@ -14,10 +14,10 @@ import static org.junit.Assert.*; * * @author chris */ -public class FooUnitTest { +public class CollectionToArrayListUnitTest { private static Collection srcCollection = new HashSet<>(); - public FooUnitTest() { + public CollectionToArrayListUnitTest() { } @BeforeClass diff --git a/java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java similarity index 98% rename from java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java index ced2ddcfc0..4d6cba7d27 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convert/iteratortolist/ConvertIteratorToListServiceUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.convert.iteratortolist; +package com.baeldung.convertiteratortolist; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java similarity index 96% rename from java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java index 6e766433d1..5e6828a3d5 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDiplicatedIdToMapServiceUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertlisttomap/ConvertListWithDuplicatedIdToMapServiceUnitTest.java @@ -11,7 +11,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; -public class ConvertListWithDiplicatedIdToMapServiceUnitTest { +public class ConvertListWithDuplicatedIdToMapServiceUnitTest { List duplicatedIdList; private ConvertListToMapService convertListService = new ConvertListToMapService(); diff --git a/java-collections-conversions/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java similarity index 99% rename from java-collections-conversions/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java index a5f684a141..4977c122e7 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.collections; +package com.baeldung.java.collections; import java.util.ArrayList; import java.util.Arrays; diff --git a/java-collections-conversions/src/test/java/org/baeldung/java/lists/ListToSTring.java b/java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java similarity index 91% rename from java-collections-conversions/src/test/java/org/baeldung/java/lists/ListToSTring.java rename to java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java index 3fc26bcb51..0fdc096d14 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/java/lists/ListToSTring.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/lists/ListToStringUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.lists; +package com.baeldung.java.lists; import java.util.Arrays; import java.util.List; @@ -7,7 +7,7 @@ import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.junit.Test; -public class ListToSTring { +public class ListToStringUnitTest { @Test public void whenListToString_thenPrintDefault() { diff --git a/java-collections-maps-2/README.md b/java-collections-maps-2/README.md index 0db83fbae7..8b33276f56 100644 --- a/java-collections-maps-2/README.md +++ b/java-collections-maps-2/README.md @@ -5,7 +5,7 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives) - [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap) -- [Guide to Java HashMap]() +- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap) - [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) - [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map) diff --git a/java-collections-maps/README.md b/java-collections-maps/README.md index 87fefe1b9d..dfd0d47dbc 100644 --- a/java-collections-maps/README.md +++ b/java-collections-maps/README.md @@ -4,7 +4,7 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) -- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap) +- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) - [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) - [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) @@ -13,4 +13,5 @@ This module contains articles about Map data structures in Java. - [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) - [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) - [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map) +- [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced) - More articles: [[next -->]](/../java-collections-maps-2) diff --git a/java-dates-2/src/main/java/com/baeldung/date/conversion/ConvertToOffsetDateTime.java b/java-dates-2/src/main/java/com/baeldung/date/conversion/ConvertToOffsetDateTime.java new file mode 100644 index 0000000000..34914962f9 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/conversion/ConvertToOffsetDateTime.java @@ -0,0 +1,19 @@ +package com.baeldung.date.conversion; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Date; + +public class ConvertToOffsetDateTime { + + public static OffsetDateTime convert(Date date) { + return date.toInstant() + .atOffset(ZoneOffset.UTC); + } + + public static OffsetDateTime convert(Date date, int hour, int minute) { + return date.toInstant() + .atOffset(ZoneOffset.ofHoursMinutes(hour, minute)); + } + +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/conversion/ConvertToOffsetDateTimeUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/conversion/ConvertToOffsetDateTimeUnitTest.java new file mode 100644 index 0000000000..c927da00c8 --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/conversion/ConvertToOffsetDateTimeUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.date.conversion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.time.OffsetDateTime; +import java.util.Date; + +import org.junit.Test; + +public class ConvertToOffsetDateTimeUnitTest { + + @Test + public void whenDateIsNotNull_thenConvertToOffsetDateTime() { + Date date = new Date(); + assertTrue(ConvertToOffsetDateTime.convert(date) instanceof OffsetDateTime); + } + + @Test + public void givenDate_whenHasOffset_thenConvertWithOffset() { + Date date = new Date(); + date.setHours(6); + date.setMinutes(30); + OffsetDateTime odt = ConvertToOffsetDateTime.convert(date, 3, 30); + assertEquals(10, odt.getHour()); + assertEquals(0, odt.getMinute()); + } + +} diff --git a/java-dates/README.md b/java-dates/README.md deleted file mode 100644 index d4657a3057..0000000000 --- a/java-dates/README.md +++ /dev/null @@ -1,24 +0,0 @@ -========= - -## Java Dates Cookbooks and Examples - -### Relevant Articles: -- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster) -- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) -- [Period and Duration in Java](http://www.baeldung.com/java-period-duration) -- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) -- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) -- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) -- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8) -- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) -- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates) -- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) -- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar) -- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) -- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) -- [Calculate Age in Java](http://www.baeldung.com/java-get-age) -- [Increment Date in Java](http://www.baeldung.com/java-increment-date) -- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date) -- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) -- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime) -- [Introduction to Joda-Time](https://www.baeldung.com/joda-time) diff --git a/java-dates/src/main/java/com/baeldung/datetime/README.md b/java-dates/src/main/java/com/baeldung/datetime/README.md deleted file mode 100644 index 7d843af9ea..0000000000 --- a/java-dates/src/main/java/com/baeldung/datetime/README.md +++ /dev/null @@ -1 +0,0 @@ -### Relevant Articles: diff --git a/java-dates/src/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-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java b/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java index 2273dfda13..de37b8d1e3 100644 --- a/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java +++ b/java-numbers/src/test/java/com/baeldung/random/JavaRandomUnitTest.java @@ -1,12 +1,10 @@ package com.baeldung.random; -import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.nio.charset.Charset; import java.util.Random; public class JavaRandomUnitTest { @@ -155,63 +153,4 @@ public class JavaRandomUnitTest { LOG.debug("{}", generatedDouble); } - // tests - random String - - @Test - public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { - final byte[] array = new byte[7]; // length is bounded by 7 - new Random().nextBytes(array); - final String generatedString = new String(array, Charset.forName("UTF-8")); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { - final int leftLimit = 97; // letter 'a' - final int rightLimit = 122; // letter 'z' - final int targetStringLength = 10; - final Random random = new Random(); - final StringBuilder buffer = new StringBuilder(targetStringLength); - - for (int i = 0; i < targetStringLength; i++) { - final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); - buffer.append((char) randomLimitedInt); - } - final String generatedString = buffer.toString(); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { - final String generatedString = RandomStringUtils.random(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { - final String generatedString = RandomStringUtils.randomAlphabetic(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { - final String generatedString = RandomStringUtils.randomAlphanumeric(10); - - LOG.debug(generatedString); - } - - @Test - public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { - final int length = 10; - final boolean useLetters = true; - final boolean useNumbers = false; - final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); - - LOG.debug(generatedString); - } - } diff --git a/java-streams-2/README.md b/java-streams-2/README.md deleted file mode 100644 index 66fbe69ed4..0000000000 --- a/java-streams-2/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Java Streams Cookbooks and Examples - -This module contains articles about the Stream API in Java. - -### Relevant Articles: -- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) -- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) -- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) -- More articles: [[<-- prev]](/java-streams) diff --git a/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java b/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java deleted file mode 100644 index a17c6a02b6..0000000000 --- a/java-streams-2/src/main/java/com/baeldung/reduce/entities/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.reduce.entities; - -public class User { - - private final String name; - private final int age; - - public User(String name, int age) { - this.name = name; - this.age = age; - } - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - @Override - public String toString() { - return "User{" + "name=" + name + ", age=" + age + '}'; - } -} diff --git a/java-streams/.gitignore b/java-streams/.gitignore deleted file mode 100644 index 3de4cc647e..0000000000 --- a/java-streams/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/java-streams/README.md b/java-streams/README.md deleted file mode 100644 index a57fdec7fa..0000000000 --- a/java-streams/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## Java Streams Cookbooks and Examples - -This module contains articles about the Stream API in Java. - -### Relevant Articles: -- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams) -- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction) -- [Java 8 and Infinite Streams](https://www.baeldung.com/java-inifinite-streams) -- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany) -- [How to Get the Last Element of a Stream in Java?](https://www.baeldung.com/java-stream-last-element) -- [“Stream has already been operated upon or closed” Exception in Java](https://www.baeldung.com/java-stream-operated-upon-or-closed-exception) -- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream) -- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices) -- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) -- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) -- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) -- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) -- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) -- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api) -- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams) -- More articles: [[next -->]](/java-streams-2) diff --git a/java-streams/pom.xml b/java-streams/pom.xml deleted file mode 100644 index bd0123e01d..0000000000 --- a/java-streams/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - 4.0.0 - java-streams - 0.1.0-SNAPSHOT - java-streams - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator.version} - provided - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - log4j - log4j - ${log4j.version} - - - org.projectlombok - lombok - ${lombok.version} - provided - - - - org.assertj - assertj-core - ${assertj.version} - test - - - com.codepoetics - protonpack - ${protonpack.version} - - - io.vavr - vavr - ${vavr.version} - - - one.util - streamex - ${streamex.version} - - - org.aspectj - aspectjrt - ${asspectj.version} - - - org.aspectj - aspectjweaver - ${asspectj.version} - - - pl.touk - throwing-function - ${throwing-function.version} - - - - - java-streams - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - -parameters - - - - - - - - 0.9.0 - 1.15 - 0.6.5 - 2.10 - 1.3 - - 3.11.1 - 1.8.9 - 3.1 - 1.8 - 1.8 - - diff --git a/java-streams/src/main/java/com/baeldung/reduce/application/Application.java b/java-streams/src/main/java/com/baeldung/reduce/application/Application.java deleted file mode 100644 index b101c86780..0000000000 --- a/java-streams/src/main/java/com/baeldung/reduce/application/Application.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.reduce.application; - -import com.baeldung.reduce.entities.User; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.Warmup; - -public class Application { - - public static void main(String[] args) throws Exception { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); - System.out.println(result1); - - int result2 = numbers.stream().reduce(0, Integer::sum); - System.out.println(result2); - - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element); - System.out.println(result3); - - String result4 = letters.stream().reduce("", String::concat); - System.out.println(result4); - - String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); - System.out.println(result5); - - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result6); - - String result7 = letters.parallelStream().reduce("", String::concat); - System.out.println(result7); - - int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - System.out.println(result8); - - org.openjdk.jmh.Main.main(args); - - } - - @Benchmark - @Fork(value = 1, warmups = 2) - @Warmup(iterations = 2) - @BenchmarkMode(Mode.AverageTime) - public void executeReduceOnParallelizedStream() { - List userList = new ArrayList<>(); - for (int i = 0; i <= 1000000; i++) { - userList.add(new User("John" + i, i)); - } - userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } - - @Benchmark - @Fork(value = 1, warmups = 2) - @Warmup(iterations = 2) - @BenchmarkMode(Mode.AverageTime) - public void executeReduceOnSequentialStream() { - List userList = new ArrayList<>(); - for (int i = 0; i <= 1000000; i++) { - userList.add(new User("John" + i, i)); - } - userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - } -} diff --git a/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java b/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java deleted file mode 100644 index 8b4af2cbe2..0000000000 --- a/java-streams/src/main/java/com/baeldung/reduce/utilities/NumberUtils.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.reduce.utilities; - -import java.util.List; -import java.util.function.BiFunction; -import java.util.logging.Level; -import java.util.logging.Logger; - -public abstract class NumberUtils { - - private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); - - public static int divideListElements(List values, Integer divider) { - return values.stream() - .reduce(0, (a, b) -> { - try { - return a / divider + b / divider; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return 0; - }); - } - - public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) { - return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); - } - - public static int divideListElementsWithApplyFunctionMethod(List values, int divider) { - BiFunction division = (a, b) -> a / b; - return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); - } - - private static int divide(int value, int factor) { - int result = 0; - try { - result = value / factor; - } catch (ArithmeticException e) { - LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); - } - return result; - } - - private static int applyFunction(BiFunction function, int a, int b) { - try { - return function.apply(a, b); - } - catch(Exception e) { - LOGGER.log(Level.INFO, "Exception occurred!"); - } - return 0; - } -} diff --git a/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java b/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java deleted file mode 100644 index 8e2ff7bf22..0000000000 --- a/java-streams/src/test/java/com/baeldung/reduce/tests/StreamReduceUnitTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.reduce.tests; - -import com.baeldung.reduce.entities.User; -import com.baeldung.reduce.utilities.NumberUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class StreamReduceUnitTest { - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, (a, b) -> a + b); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - int result = numbers.stream().reduce(0, Integer::sum); - assertThat(result).isEqualTo(21); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (a, b) -> a + b); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase()); - assertThat(result).isEqualTo("ABCDE"); - } - - @Test - public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { - List users = Arrays.asList(new User("John", 30), new User("Julie", 35)); - int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); - assertThat(result).isEqualTo(65); - } - - @Test - public void givenStringList_whenReduceWithParallelStream_thenCorrect() { - List letters = Arrays.asList("a", "b", "c", "d", "e"); - String result = letters.parallelStream().reduce("", String::concat); - assertThat(result).isEqualTo("abcde"); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); - } - - @Test - public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { - List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); - assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); - } -} diff --git a/java-streams/src/test/resources/.gitignore b/java-streams/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-streams/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-2/README.md b/java-strings-2/README.md deleted file mode 100644 index ced813163d..0000000000 --- a/java-strings-2/README.md +++ /dev/null @@ -1,27 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about strings in Java. - -### Relevant Articles: - -- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) -- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) -- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) -- [Java – Generate Random String](https://www.baeldung.com/java-random-string) -- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) -- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) -- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) -- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) -- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) -- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) -- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) -- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) -- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) -- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) -- [Checking for Empty or Blank Strings in Java](https://www.baeldung.com/java-blank-empty-strings) -- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) -- [Java Multi-line String](https://www.baeldung.com/java-multiline-string) -- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) -- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string) -- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case) -- More articles: [[<-- prev>]](/java-strings) [[next -->]](/java-strings-3) diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml deleted file mode 100755 index be47b1ec89..0000000000 --- a/java-strings-2/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - 4.0.0 - java-strings-2 - 0.1.0-SNAPSHOT - jar - java-strings-2 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-core.version} - - - com.ibm.icu - icu4j - ${icu4j.version} - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - commons-io - commons-io - ${commons-io.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - org.passay - passay - ${passay.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - com.vdurmont - emoji-java - ${emoji-java.version} - - - org.ahocorasick - ahocorasick - ${ahocorasick.version} - - - javax.validation - validation-api - ${validation-api.version} - - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - - - - - java-strings-2 - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - - - - 3.8.1 - 1.10 - 1.3.1 - - 3.6.1 - 4.0.0 - 0.4.0 - 61.1 - 28.0-jre - 1.4 - 2.0.0.Final - 6.0.2.Final - 3.0.0 - 2.2.6 - - - \ No newline at end of file diff --git a/java-strings-2/src/test/resources/.gitignore b/java-strings-2/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-2/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-3/README.md b/java-strings-3/README.md deleted file mode 100644 index 6276dfc621..0000000000 --- a/java-strings-3/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about strings in Java. - -### Relevant Articles: -- [Java String equalsIgnoreCase()](https://www.baeldung.com/java-string-equalsignorecase) -- [Finding the Difference Between Two Strings](https://www.baeldung.com/java-difference-between-two-strings) -- [Counting Words in a String](https://www.baeldung.com/java-word-counting) -- More articles: [[<-- prev>]](/java-strings-2) diff --git a/java-strings-3/pom.xml b/java-strings-3/pom.xml deleted file mode 100644 index 4589780c15..0000000000 --- a/java-strings-3/pom.xml +++ /dev/null @@ -1,161 +0,0 @@ - - 4.0.0 - java-strings-3 - 0.1.0-SNAPSHOT - jar - java-strings-3 - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-core.version} - - - com.ibm.icu - icu4j - ${icu4j.version} - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - commons-io - commons-io - ${commons-io.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - junit - junit - ${junit.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.bitbucket.cowwoc - diff-match-patch - 1.2 - test - - - - - org.passay - passay - ${passay.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - com.vdurmont - emoji-java - ${emoji-java.version} - - - org.ahocorasick - ahocorasick - ${ahocorasick.version} - - - javax.validation - validation-api - ${validation-api.version} - - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - - - - - java-strings-3 - - - src/main/resources - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - -parameters - - - - - - - 3.8.1 - 1.10 - 1.3.1 - - 3.6.1 - 4.0.0 - 0.4.0 - 61.1 - 28.0-jre - 1.4 - 2.0.0.Final - 6.0.2.Final - 3.0.0 - 2.2.6 - - - \ No newline at end of file diff --git a/java-strings-3/src/main/resources/.gitignore b/java-strings-3/src/main/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-3/src/main/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-3/src/test/resources/.gitignore b/java-strings-3/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-3/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings-ops/README.md b/java-strings-ops/README.md deleted file mode 100644 index 1300cf028e..0000000000 --- a/java-strings-ops/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about operations on strings in Java. - -### Relevant Articles: -- [Check If a String Is a Palindrome](https://www.baeldung.com/java-palindrome) -- [Comparing Strings in Java](https://www.baeldung.com/java-compare-strings) -- [Check If a String Is Numeric in Java](https://www.baeldung.com/java-check-string-number) -- [Get Substring from String in Java](https://www.baeldung.com/java-substring) -- [How to Remove the Last Character of a String?](https://www.baeldung.com/java-remove-last-character-of-string) -- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) -- [Count Occurrences of a Char in a String](https://www.baeldung.com/java-count-chars) -- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) -- [Split a String in Java](https://www.baeldung.com/java-split-string) -- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) -- [Java toString() Method](https://www.baeldung.com/java-tostring) diff --git a/java-strings-ops/src/test/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/resources/.gitignore b/java-strings-ops/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings-ops/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/java-strings/README.md b/java-strings/README.md deleted file mode 100644 index 17b74231a4..0000000000 --- a/java-strings/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Java Strings Cookbooks and Examples - -This module contains articles about strings in Java. - -### Relevant Articles: -- [String Operations with Java Streams](https://www.baeldung.com/java-stream-operations-on-strings) -- [Use char[] Array Over a String for Manipulating Passwords in Java?](https://www.baeldung.com/java-storing-passwords) -- [Compact Strings in Java 9](https://www.baeldung.com/java-9-compact-string) -- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) -- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) -- [String Performance Hints](https://www.baeldung.com/java-string-performance) -- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) -- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) -- [Remove or Replace Part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) -- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) -- More articles: [[next -->]](/java-strings-2) diff --git a/java-strings/src/main/resources/data.csv b/java-strings/src/main/resources/data.csv deleted file mode 100644 index ec4ac10443..0000000000 --- a/java-strings/src/main/resources/data.csv +++ /dev/null @@ -1,3 +0,0 @@ -1|IND|India -2|MY|Malaysia -3|AU|Australia diff --git a/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java deleted file mode 100644 index 3488f8b390..0000000000 --- a/java-strings/src/test/java/com/baeldung/CharArrayToStringUnitTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class CharArrayToStringUnitTest { - - @Test - public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = new String(charArray); - String expectedValue = "character"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = new String(charArray, 4, 3); - String expectedValue = "act"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.copyValueOf(charArray); - String expectedValue = "character"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.copyValueOf(charArray, 0, 4); - String expectedValue = "char"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.valueOf(charArray); - String expectedValue = "character"; - - assertEquals(expectedValue, result); - } - - @Test - public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() { - char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; - String result = String.valueOf(charArray, 3, 4); - String expectedValue = "ract"; - - assertEquals(expectedValue, result); - } -} diff --git a/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java deleted file mode 100644 index cd996e58e2..0000000000 --- a/java-strings/src/test/java/com/baeldung/StringToCharArrayUnitTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class StringToCharArrayUnitTest { - - @Test - public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { - String givenString = "characters"; - - char[] result = givenString.toCharArray(); - - char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; - - assertArrayEquals(expectedCharArray, result); - } - -} diff --git a/java-strings/src/test/resources/.gitignore b/java-strings/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/java-strings/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/javaxval/README.md b/javaxval/README.md index c2c392b276..33ce4eae5b 100644 --- a/javaxval/README.md +++ b/javaxval/README.md @@ -9,4 +9,4 @@ This module contains articles about Bean Validation. - [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank) - [Javax BigDecimal Validation](https://www.baeldung.com/javax-bigdecimal-validation) - [Grouping Javax Validation Constraints](https://www.baeldung.com/javax-validation-groups) -- [Javax Validations for Enums](https://www.baeldung.com/javax-validations-enums) +- [Validations for Enum Types](https://www.baeldung.com/javax-validations-enums) diff --git a/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java b/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java new file mode 100644 index 0000000000..b9fcfdf4d4 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javaxval/messageinterpolator/Person.java @@ -0,0 +1,42 @@ +package org.baeldung.javaxval.messageinterpolator; + +import javax.validation.constraints.Email; +import javax.validation.constraints.Min; +import javax.validation.constraints.Size; + +public class Person { + + @Size(min = 10, max = 100, message = "Name should be between {min} and {max} characters") + private String name; + + @Min(value = 18, message = "Age should not be less than {value}") + private int age; + + @Email(message = "Email address should be in a correct format: ${validatedValue}") + private String email; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java b/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java new file mode 100644 index 0000000000..6ecb916ab4 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java @@ -0,0 +1,70 @@ +package org.baeldung.javaxval.messageinterpolator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ParameterMessageInterpolaterIntegrationTest { + + private static Validator validator; + + @BeforeClass + public static void beforeClass() { + ValidatorFactory validatorFactory = Validation.byDefaultProvider() + .configure() + .messageInterpolator(new ParameterMessageInterpolator()) + .buildValidatorFactory(); + + validator = validatorFactory.getValidator(); + } + + @Test + public void givenNameLengthLessThanMin_whenValidate_thenValidationFails() { + Person person = new Person(); + person.setName("John Doe"); + person.setAge(18); + + Set> violations = validator.validate(person); + assertEquals(1, violations.size()); + + ConstraintViolation violation = violations.iterator().next(); + assertEquals("Name should be between 10 and 100 characters", violation.getMessage()); + } + + @Test + public void givenAgeIsLessThanMin_whenValidate_thenValidationFails() { + Person person = new Person(); + person.setName("John Stephaner Doe"); + person.setAge(16); + + Set> violations = validator.validate(person); + assertEquals(1, violations.size()); + + ConstraintViolation violation = violations.iterator().next(); + assertEquals("Age should not be less than 18", violation.getMessage()); + } + + @Test + public void givenEmailIsMalformed_whenValidate_thenValidationFails() { + Person person = new Person(); + person.setName("John Stephaner Doe"); + person.setAge(18); + person.setEmail("johndoe.dev"); + + Set> violations = validator.validate(person); + assertEquals(1, violations.size()); + + ConstraintViolation violation = violations.iterator().next(); + assertEquals("Email address should be in a correct format: ${validatedValue}", violation.getMessage()); + } + +} diff --git a/jaxb/README.md b/jaxb/README.md index d9d16ab70b..a471ccd39d 100644 --- a/jaxb/README.md +++ b/jaxb/README.md @@ -5,4 +5,3 @@ This module contains articles about JAXB. ### Relevant Articles: - [Guide to JAXB](https://www.baeldung.com/jaxb) - [Unmarshalling Dates Using JAXB](https://www.baeldung.com/jaxb-unmarshalling-dates) - diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml index 17163ba23c..60765f6bc2 100644 --- a/jee-kotlin/pom.xml +++ b/jee-kotlin/pom.xml @@ -230,7 +230,7 @@ - wildfly-remote-arquillian + wildfly-remote-arquillian-disabled org.jboss.resteasy diff --git a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java index b91b47cb1f..d48a3a96da 100644 --- a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java +++ b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java @@ -36,7 +36,7 @@ public class StudentResourceIntegrationTest { .withMavenCentralRepo(true) .withClassPathResolution(true) .loadPomFromFile("pom.xml") - .resolve("org.jetbrains.kotlin:kotlin-stdlib") + .resolve("org.jetbrains.kotlin:kotlin-stdlib:1.3.41") .withTransitivity() .as(JavaArchive.class); diff --git a/jersey/README.md b/jersey/README.md index 8537e07358..366e7665f3 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -10,4 +10,3 @@ This module contains articles about Jersey. - [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test) - [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters) - [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers) - diff --git a/jhipster-5/README.md b/jhipster-5/README.md index ba05641af0..e4a6b3c3a0 100644 --- a/jhipster-5/README.md +++ b/jhipster-5/README.md @@ -1,3 +1,6 @@ ## JHipster 5 This module contains articles about JHipster 5. This is an aggregator module, articles are in the relevant submodules. + +### Relevant Articles: +- [JHipster Authentication with an External Service](https://www.baeldung.com/jhipster-authentication-external-service) diff --git a/jta/pom.xml b/jta/pom.xml index b7e39c66e1..1e86a0144c 100644 --- a/jta/pom.xml +++ b/jta/pom.xml @@ -30,12 +30,6 @@ spring-boot-starter - - org.springframework.boot - spring-boot-starter-test - test - - org.hsqldb hsqldb diff --git a/libraries-2/README.md b/libraries-2/README.md index fd1f73c386..95c454edbb 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -18,6 +18,7 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map) - [Guide to MapDB](https://www.baeldung.com/mapdb) - [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos) -- [JasperReports with Spring](https://www.baeldung.com/spring-jasper) +- [JasperReports with Spring](https://www.baeldung.com/spring-jasper)] +- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) - More articles [[<-- prev]](/libraries) diff --git a/libraries-3/README.md b/libraries-3/README.md new file mode 100644 index 0000000000..a6c6b190ab --- /dev/null +++ b/libraries-3/README.md @@ -0,0 +1,9 @@ +## Libraries-3 + +This module contains articles about various Java libraries. +These are small libraries that are relatively easy to use and do not require any separate module of their own. + +The code examples related to different libraries are each in their own module. + +Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. + diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml new file mode 100644 index 0000000000..214e87287d --- /dev/null +++ b/libraries-3/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + libraries-3 + libraries-3 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + jboss-public-repository-group + JBoss Public Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + + true + never + + + true + daily + + + + + + + com.beust + jcommander + ${jcommander.version} + + + org.projectlombok + lombok + ${lombok.version} + + + + + 1.78 + 1.18.6 + UTF-8 + 1.8 + 1.8 + + diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java b/libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java new file mode 100644 index 0000000000..56a74ecf21 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java @@ -0,0 +1,37 @@ +package com.baeldung.jcommander.helloworld; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; + +public class HelloWorldApp { + + /* + * Execute: + * mvn exec:java -Dexec.mainClass=com.baeldung.jcommander.helloworld.HelloWorldApp -q \ + * -Dexec.args="--name JavaWorld" + */ + public static void main(String[] args) { + HelloWorldArgs jArgs = new HelloWorldArgs(); + JCommander helloCmd = JCommander + .newBuilder() + .addObject(jArgs) + .build(); + + helloCmd.parse(args); + System.out.println("Hello " + jArgs.getName()); + } +} + +class HelloWorldArgs { + + @Parameter( + names = "--name", + description = "User name", + required = true + ) + private String name; + + public String getName() { + return name; + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java new file mode 100644 index 0000000000..029e7eed01 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java @@ -0,0 +1,23 @@ +package com.baeldung.jcommander.usagebilling; + +import com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling; + +public class UsageBasedBillingApp { + + /* + * Entry-point: invokes the cli passing the command-line args + * + * Invoking "Submit" sub-command: + * mvn exec:java \ + -Dexec.mainClass=com.baeldung.jcommander.usagebilling.UsageBasedBillingApp -q \ + -Dexec.args="submit --customer cb898e7a-f2a0-46d2-9a09-531f1cee1839 --subscription subscriptionPQRMN001 --pricing-type PRE_RATED --timestamp 2019-10-03T10:58:00 --quantity 7 --price 24.56" + * + * Invoking "Fetch" sub-command: + * mvn exec:java \ + -Dexec.mainClass=com.baeldung.jcommander.usagebilling.UsageBasedBillingApp -q \ + -Dexec.args="fetch --customer cb898e7a-f2a0-46d2-9a09-531f1cee1839 --subscription subscriptionPQRMN001 subscriptionPQRMN002 subscriptionPQRMN003 --itemized" + */ + public static void main(String[] args) { + new UsageBasedBilling().run(args); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java new file mode 100644 index 0000000000..ea6b18af53 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java @@ -0,0 +1,67 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.baeldung.jcommander.usagebilling.cli.splitter.ColonParameterSplitter; +import com.baeldung.jcommander.usagebilling.cli.validator.UUIDValidator; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; +import com.baeldung.jcommander.usagebilling.service.FetchCurrentChargesService; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import lombok.Getter; + +import java.util.List; + +import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.*; +import static com.baeldung.jcommander.usagebilling.service.FetchCurrentChargesService.getDefault; + +@Parameters( + commandNames = { FETCH_CMD }, + commandDescription = "Fetch charges for a customer in the current month, can be itemized or aggregated" +) +@Getter +class FetchCurrentChargesCommand { + + FetchCurrentChargesCommand() { + } + + private FetchCurrentChargesService service = getDefault(); + + @Parameter(names = "--help", help = true) + private boolean help; + + @Parameter( + names = { "--customer", "-C" }, + description = "Id of the Customer who's using the services", + validateWith = UUIDValidator.class, + order = 1, + required = true + ) + private String customerId; + + @Parameter( + names = { "--subscription", "-S" }, + description = "Filter charges for specific subscription Ids, includes all subscriptions if no value is specified", + variableArity = true, + splitter = ColonParameterSplitter.class, + order = 2 + ) + private List subscriptionIds; + + @Parameter( + names = { "--itemized" }, + description = "Whether the response should contain breakdown by subscription, only aggregate values are returned by default", + order = 3 + ) + private boolean itemized; + + void fetch() { + CurrentChargesRequest req = CurrentChargesRequest.builder() + .customerId(customerId) + .subscriptionIds(subscriptionIds) + .itemized(itemized) + .build(); + + CurrentChargesResponse response = service.fetch(req); + System.out.println(response); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java new file mode 100644 index 0000000000..d3516b19d3 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java @@ -0,0 +1,96 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.baeldung.jcommander.usagebilling.cli.converter.ISO8601TimestampConverter; +import com.baeldung.jcommander.usagebilling.cli.validator.UUIDValidator; +import com.baeldung.jcommander.usagebilling.model.UsageRequest; +import com.baeldung.jcommander.usagebilling.model.UsageRequest.PricingType; +import com.baeldung.jcommander.usagebilling.service.SubmitUsageService; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; +import lombok.Getter; + +import java.math.BigDecimal; +import java.time.Instant; + +import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.*; +import static com.baeldung.jcommander.usagebilling.service.SubmitUsageService.getDefault; + +@Parameters( + commandNames = { SUBMIT_CMD }, + commandDescription = "Submit usage for a given customer and subscription, accepts one usage item" +) +@Getter +class SubmitUsageCommand { + + SubmitUsageCommand() { + } + + private SubmitUsageService service = getDefault(); + + @Parameter(names = "--help", help = true) + private boolean help; + + @Parameter( + names = { "--customer", "-C" }, + description = "Id of the Customer who's using the services", + validateWith = UUIDValidator.class, + order = 1, + required = true + ) + private String customerId; + + @Parameter( + names = { "--subscription", "-S" }, + description = "Id of the Subscription that was purchased", + order = 2, + required = true + ) + private String subscriptionId; + + @Parameter( + names = { "--pricing-type", "-P" }, + description = "Pricing type of the usage reported", + order = 3, + required = true + ) + private PricingType pricingType; + + @Parameter( + names = { "--quantity" }, + description = "Used quantity; reported quantity is added over the billing period", + order = 3, + required = true + ) + private Integer quantity; + + @Parameter( + names = { "--timestamp" }, + description = "Timestamp of the usage event, must lie in the current billing period", + converter = ISO8601TimestampConverter.class, + order = 4, + required = true + ) + private Instant timestamp; + + @Parameter( + names = { "--price" }, + description = "If PRE_RATED, unit price to be applied per unit of usage quantity reported", + order = 5 + ) + private BigDecimal price; + + void submit() { + + UsageRequest req = UsageRequest.builder() + .customerId(customerId) + .subscriptionId(subscriptionId) + .pricingType(pricingType) + .quantity(quantity) + .timestamp(timestamp) + .price(price) + .build(); + + String reqId = service.submit(req); + System.out.println("Generated Request Id for reference: " + reqId); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java new file mode 100644 index 0000000000..a531a68644 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java @@ -0,0 +1,80 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.UnixStyleUsageFormatter; + +public class UsageBasedBilling { + + static final String SUBMIT_CMD = "submit"; + static final String FETCH_CMD = "fetch"; + + private JCommander jCommander; + private SubmitUsageCommand submitUsageCmd; + private FetchCurrentChargesCommand fetchChargesCmd; + + public UsageBasedBilling() { + this.submitUsageCmd = new SubmitUsageCommand(); + this.fetchChargesCmd = new FetchCurrentChargesCommand(); + jCommander = JCommander.newBuilder() + .addObject(this) + .addCommand(submitUsageCmd) + .addCommand(fetchChargesCmd) + .build(); + + setUsageFormatter(SUBMIT_CMD); + setUsageFormatter(FETCH_CMD); + } + + public void run(String[] args) { + String parsedCmdStr; + try { + jCommander.parse(args); + parsedCmdStr = jCommander.getParsedCommand(); + + switch (parsedCmdStr) { + case SUBMIT_CMD: + if (submitUsageCmd.isHelp()) { + getSubCommandHandle(SUBMIT_CMD).usage(); + } + System.out.println("Parsing usage request..."); + submitUsageCmd.submit(); + break; + + case FETCH_CMD: + if (fetchChargesCmd.isHelp()) { + getSubCommandHandle(SUBMIT_CMD).usage(); + } + System.out.println("Preparing fetch query..."); + fetchChargesCmd.fetch(); + + break; + + default: + System.err.println("Invalid command: " + parsedCmdStr); + } + } catch (ParameterException e) { + System.err.println(e.getLocalizedMessage()); + parsedCmdStr = jCommander.getParsedCommand(); + if (parsedCmdStr != null) { + getSubCommandHandle(parsedCmdStr).usage(); + } else { + jCommander.usage(); + } + } + } + + private JCommander getSubCommandHandle(String command) { + JCommander cmd = jCommander.getCommands().get(command); + + if (cmd == null) { + System.err.println("Invalid command: " + command); + } + return cmd; + } + + private void setUsageFormatter(String subCommand) { + JCommander cmd = getSubCommandHandle(subCommand); + cmd.setUsageFormatter(new UnixStyleUsageFormatter(cmd)); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java new file mode 100644 index 0000000000..e54865a811 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java @@ -0,0 +1,33 @@ +package com.baeldung.jcommander.usagebilling.cli.converter; + +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.converters.BaseConverter; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +import static java.lang.String.format; + +public class ISO8601TimestampConverter extends BaseConverter { + + private static final DateTimeFormatter TS_FORMATTER = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss"); + + public ISO8601TimestampConverter(String optionName) { + super(optionName); + } + + @Override + public Instant convert(String value) { + try { + return LocalDateTime + .parse(value, TS_FORMATTER) + .atOffset(ZoneOffset.UTC) + .toInstant(); + } catch (DateTimeParseException e) { + throw new ParameterException(getErrorString(value, format("an ISO-8601 formatted timestamp (%s)", TS_FORMATTER.toString()))); + } + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java new file mode 100644 index 0000000000..f24c028123 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java @@ -0,0 +1,15 @@ +package com.baeldung.jcommander.usagebilling.cli.splitter; + +import com.beust.jcommander.converters.IParameterSplitter; + +import java.util.List; + +import static java.util.Arrays.asList; + +public class ColonParameterSplitter implements IParameterSplitter { + + @Override + public List split(String value) { + return asList(value.split(":")); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java new file mode 100644 index 0000000000..a72912f7d0 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java @@ -0,0 +1,26 @@ +package com.baeldung.jcommander.usagebilling.cli.validator; + +import com.beust.jcommander.IParameterValidator; +import com.beust.jcommander.ParameterException; + +import java.util.regex.Pattern; + +public class UUIDValidator implements IParameterValidator { + + private static final String UUID_REGEX = + "[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; + + @Override + public void validate(String name, String value) throws ParameterException { + if (!isValidUUID(value)) { + throw new ParameterException( + "String parameter " + value + " is not a valid UUID."); + } + } + + private boolean isValidUUID(String value) { + return Pattern + .compile(UUID_REGEX) + .matcher(value).matches(); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java new file mode 100644 index 0000000000..93dd7a5732 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java @@ -0,0 +1,16 @@ +package com.baeldung.jcommander.usagebilling.model; + +import lombok.*; + +import java.util.List; + +@NoArgsConstructor(access = AccessLevel.PACKAGE) +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@Builder +@Getter +public class CurrentChargesRequest { + + private String customerId; + private List subscriptionIds; + private boolean itemized; +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java new file mode 100644 index 0000000000..865a6e4a3d --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java @@ -0,0 +1,56 @@ +package com.baeldung.jcommander.usagebilling.model; + +import lombok.*; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; + +@NoArgsConstructor(access = AccessLevel.PACKAGE) +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@Builder +@Getter +public class CurrentChargesResponse { + + private String customerId; + private BigDecimal amountDue; + private List lineItems; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb + .append("Current Month Charges: {") + .append("\n\tcustomer: ") + .append(this.customerId) + .append("\n\ttotalAmountDue: ") + .append(this.amountDue.setScale(2, RoundingMode.HALF_UP)) + .append("\n\tlineItems: ["); + + for (LineItem li : this.lineItems) { + sb + .append("\n\t\t{") + .append("\n\t\t\tsubscription: ") + .append(li.subscriptionId) + .append("\n\t\t\tamount: ") + .append(li.amount.setScale(2, RoundingMode.HALF_UP)) + .append("\n\t\t\tquantity: ") + .append(li.quantity) + .append("\n\t\t},"); + } + + sb.append("\n\t]\n}\n"); + return sb.toString(); + } + + @NoArgsConstructor(access = AccessLevel.PACKAGE) + @AllArgsConstructor(access = AccessLevel.PACKAGE) + @Builder + @Getter + public static class LineItem { + + private String subscriptionId; + private BigDecimal amount; + private Integer quantity; + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java new file mode 100644 index 0000000000..2785474acf --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java @@ -0,0 +1,50 @@ +package com.baeldung.jcommander.usagebilling.model; + +import lombok.*; + +import java.math.BigDecimal; +import java.time.Instant; + +@NoArgsConstructor(access = AccessLevel.PACKAGE) +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@Builder +@Getter +public class UsageRequest { + + private String customerId; + private String subscriptionId; + private PricingType pricingType; + private Integer quantity; + private BigDecimal price; + private Instant timestamp; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb + .append("\nUsage: {") + .append("\n\tcustomer: ") + .append(this.customerId) + .append("\n\tsubscription: ") + .append(this.subscriptionId) + .append("\n\tquantity: ") + .append(this.quantity) + .append("\n\ttimestamp: ") + .append(this.timestamp) + .append("\n\tpricingType: ") + .append(this.pricingType); + + if (PricingType.PRE_RATED == this.pricingType) { + sb + .append("\n\tpreRatedAt: ") + .append(this.price); + } + + sb.append("\n}\n"); + return sb.toString(); + } + + public enum PricingType { + PRE_RATED, UNRATED + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java new file mode 100644 index 0000000000..6436d49875 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java @@ -0,0 +1,68 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse.LineItem; + +import java.math.BigDecimal; +import java.util.List; +import java.util.UUID; + +import static java.lang.String.format; +import static java.util.Arrays.asList; +import static java.util.Arrays.fill; +import static java.util.Collections.emptyList; +import static java.util.concurrent.ThreadLocalRandom.current; +import static java.util.stream.Collectors.toList; + +class DefaultFetchCurrentChargesService implements FetchCurrentChargesService { + + @Override + public CurrentChargesResponse fetch(CurrentChargesRequest request) { + List subscriptions = request.getSubscriptionIds(); + + if (subscriptions == null || subscriptions.isEmpty()) { + System.out.println("Fetching ALL charges for customer: " + request.getCustomerId()); + subscriptions = mockSubscriptions(); + + } else { + System.out.println(format("Fetching charges for customer: %s and subscriptions: %s", request.getCustomerId(), subscriptions)); + } + + CurrentChargesResponse charges = mockCharges(request.getCustomerId(), subscriptions, request.isItemized()); + System.out.println("Fetched charges..."); + return charges; + } + + private CurrentChargesResponse mockCharges(String customerId, List subscriptions, boolean itemized) { + List lineItems = mockLineItems(subscriptions); + BigDecimal amountDue = lineItems + .stream() + .map(li -> li.getAmount()) + .reduce(new BigDecimal("0"), BigDecimal::add); + + return CurrentChargesResponse + .builder() + .customerId(customerId) + .lineItems(itemized ? lineItems : emptyList()) + .amountDue(amountDue) + .build(); + } + + private List mockLineItems(List subscriptions) { + return subscriptions + .stream() + .map(subscription -> LineItem.builder() + .subscriptionId(subscription) + .quantity(current().nextInt(20)) + .amount(new BigDecimal(current().nextDouble(1_000))) + .build()) + .collect(toList()); + } + + private List mockSubscriptions() { + String[] subscriptions = new String[5]; + fill(subscriptions, UUID.randomUUID().toString()); + return asList(subscriptions); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java new file mode 100644 index 0000000000..44ac9e9ed7 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java @@ -0,0 +1,16 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.UsageRequest; + +import java.util.UUID; + +class DefaultSubmitUsageService implements SubmitUsageService { + + @Override + public String submit(UsageRequest request) { + System.out.println("Submitting usage..." + request); + + System.out.println("Submitted usage successfully..."); + return UUID.randomUUID().toString(); + } +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java new file mode 100644 index 0000000000..2cc56658ff --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java @@ -0,0 +1,13 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; + +public interface FetchCurrentChargesService { + + static FetchCurrentChargesService getDefault() { + return new DefaultFetchCurrentChargesService(); + } + + CurrentChargesResponse fetch(CurrentChargesRequest request); +} diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java new file mode 100644 index 0000000000..2a29e6e474 --- /dev/null +++ b/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java @@ -0,0 +1,12 @@ +package com.baeldung.jcommander.usagebilling.service; + +import com.baeldung.jcommander.usagebilling.model.UsageRequest; + +public interface SubmitUsageService { + + static SubmitUsageService getDefault() { + return new DefaultSubmitUsageService(); + } + + String submit(UsageRequest request); +} diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java b/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java new file mode 100644 index 0000000000..48b3ac2896 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.jcommander.helloworld; + +import com.beust.jcommander.JCommander; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class HelloWorldAppUnitTest { + + @Test + public void whenJCommanderInvokedWithArgs_thenArgsParsed() { + + HelloWorldArgs jArgs = new HelloWorldArgs(); + JCommander helloCmd = JCommander + .newBuilder() + .addObject(jArgs) + .build(); + + // when + String[] argv = new String[] { + "--name", "JavaWorld" + }; + helloCmd.parse(argv); + + // then + assertEquals("JavaWorld", jArgs.getName()); + } +} diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java new file mode 100644 index 0000000000..b639661c39 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.beust.jcommander.JCommander; +import org.junit.Test; + +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertThat; + +public class FetchCurrentChargesCommandUnitTest { + + private JCommander jc = JCommander.newBuilder() + .addObject(new FetchCurrentChargesCommand()) + .build(); + + @Test + public void whenParsedMultipleSubscriptionsParameter_thenParameterSubscriptionsIsPopulated() { + FetchCurrentChargesCommand cmd = (FetchCurrentChargesCommand) jc + .getObjects() + .get(0); + + jc.parse(new String[] { + "-C", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "-S", "subscriptionA001", + "-S", "subscriptionA002", + "-S", "subscriptionA003", + }); + + assertThat(cmd.getSubscriptionIds(), + contains("subscriptionA001", "subscriptionA002", "subscriptionA003")); + } + + @Test + public void whenParsedSubscriptionsColonSeparatedParameter_thenParameterSubscriptionsIsPopulated() { + FetchCurrentChargesCommand cmd = (FetchCurrentChargesCommand) jc + .getObjects() + .get(0); + + jc.parse(new String[] { + "-C", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "-S", "subscriptionA001:subscriptionA002:subscriptionA003", + }); + + assertThat(cmd.getSubscriptionIds(), + contains("subscriptionA001", "subscriptionA002", "subscriptionA003")); + } + + @Test + public void whenParsedSubscriptionsWithVariableArity_thenParameterSubscriptionsIsPopulated() { + FetchCurrentChargesCommand cmd = (FetchCurrentChargesCommand) jc + .getObjects() + .get(0); + + jc.parse(new String[] { + "-C", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "-S", "subscriptionA001", "subscriptionA002", "subscriptionA003", + }); + + assertThat(cmd.getSubscriptionIds(), + contains("subscriptionA001", "subscriptionA002", "subscriptionA003")); + } +} diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java new file mode 100644 index 0000000000..d6ce132053 --- /dev/null +++ b/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.jcommander.usagebilling.cli; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.ParameterException; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SubmitUsageCommandUnitTest { + + private JCommander jc = JCommander.newBuilder() + .addObject(new SubmitUsageCommand()) + .build(); + + @Test + public void whenParsedCustomerParameter_thenParameterOfTypeStringIsPopulated() { + jc.parse(new String[] { + "--customer", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "--subscription", "subscriptionPQRMN001", + "--pricing-type", "PRE_RATED", + "--timestamp", "2019-10-03T10:58:00", + "--quantity", "7", + "--price", "24.56" + }); + + SubmitUsageCommand cmd = (SubmitUsageCommand) jc + .getObjects() + .get(0); + assertEquals("cb898e7a-f2a0-46d2-9a09-531f1cee1839", cmd.getCustomerId()); + } + + @Test + public void whenParsedTimestampParameter_thenParameterOfTypeInstantIsPopulated() { + jc.parse(new String[] { + "--customer", "cb898e7a-f2a0-46d2-9a09-531f1cee1839", + "--subscription", "subscriptionPQRMN001", + "--pricing-type", "PRE_RATED", + "--timestamp", "2019-10-03T10:58:00", + "--quantity", "7", + "--price", "24.56" + }); + + SubmitUsageCommand cmd = (SubmitUsageCommand) jc + .getObjects() + .get(0); + assertEquals("2019-10-03T10:58:00Z", cmd + .getTimestamp() + .toString()); + } + + @Test(expected = ParameterException.class) + public void whenParsedCustomerIdNotUUID_thenParameterException() { + jc.parse(new String[] { + "--customer", "customer001", + "--subscription", "subscriptionPQRMN001", + "--pricing-type", "PRE_RATED", + "--timestamp", "2019-10-03T10:58:00", + "--quantity", "7", + "--price", "24.56" + }); + } +} diff --git a/libraries-data-io/src/main/resources/csv/twoColumn.csv b/libraries-data-io/src/main/resources/csv/twoColumn.csv new file mode 100644 index 0000000000..56d8fa1901 --- /dev/null +++ b/libraries-data-io/src/main/resources/csv/twoColumn.csv @@ -0,0 +1,5 @@ +colA, ColB +A, B +C, D +G, G +G, F \ No newline at end of file diff --git a/libraries-data-io/src/main/resources/csv/writtenAll.csv b/libraries-data-io/src/main/resources/csv/writtenAll.csv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries-data-io/src/main/resources/csv/writtenBean.csv b/libraries-data-io/src/main/resources/csv/writtenBean.csv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries-data-io/src/main/resources/csv/writtenOneByOne.csv b/libraries-data-io/src/main/resources/csv/writtenOneByOne.csv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries-primitive/README.MD b/libraries-primitive/README.MD index 086cdc0d2d..9cb89f3552 100644 --- a/libraries-primitive/README.MD +++ b/libraries-primitive/README.MD @@ -2,4 +2,3 @@ - [Guide to FastUtil](https://www.baeldung.com/fastutil) - [Primitive Collections in Eclipse Collections](https://www.baeldung.com/java-eclipse-primitive-collections) - diff --git a/libraries-security/README.md b/libraries-security/README.md index 68badcf12d..819bc866cf 100644 --- a/libraries-security/README.md +++ b/libraries-security/README.md @@ -9,3 +9,4 @@ This module contains articles about security libraries. - [Guide to Google Tink](https://www.baeldung.com/google-tink) - [Introduction to BouncyCastle with Java](https://www.baeldung.com/java-bouncy-castle) - [Intro to Jasypt](https://www.baeldung.com/jasypt) +- [Digital Signature in Java](https://www.baeldung.com/java-digital-signature) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index a2fbed31b2..86c9bd52e1 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -125,19 +125,6 @@ ${java-hamcrest.version} test - - - net.serenity-bdd - serenity-core - ${serenity.version} - test - - - org.asciidoctor - asciidoctorj - - - org.asciidoctor asciidoctor-maven-plugin diff --git a/linux-bash/json/src/main/bash/fruit.json b/linux-bash/json/src/main/bash/fruit.json new file mode 100644 index 0000000000..392d2290ae --- /dev/null +++ b/linux-bash/json/src/main/bash/fruit.json @@ -0,0 +1 @@ +{"fruit":{"name":"apple","color":"green","price":1.20}} diff --git a/linux-bash/json/src/main/bash/fruits.json b/linux-bash/json/src/main/bash/fruits.json new file mode 100644 index 0000000000..114a9a35cc --- /dev/null +++ b/linux-bash/json/src/main/bash/fruits.json @@ -0,0 +1,17 @@ +[ + { + "name": "apple", + "color": "green", + "price": 1.2 + }, + { + "name": "banana", + "color": "yellow", + "price": 0.5 + }, + { + "name": "kiwi", + "color": "green", + "price": 1.25 + } +] diff --git a/linux-bash/json/src/main/bash/jq.sh b/linux-bash/json/src/main/bash/jq.sh new file mode 100755 index 0000000000..786be304db --- /dev/null +++ b/linux-bash/json/src/main/bash/jq.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +#3.1. Beautify JSON +echo '{"fruit":{"name":"apple","color":"green","price":1.20}}' | jq '.' +jq '.' fruit.json +curl http://api.open-notify.org/iss-now.json | jq '.' + +#3.2. Accessing Properties +jq '.fruit' fruit.json +jq '.fruit.color' fruit.json +jq '.fruit.color,.fruit.price' fruit.json +echo '{ "with space": "hello" }' | jq '."with space"' + +#4.1. Iteration +echo '["x","y","z"]' | jq '.[]' +jq '.[] | .name' fruits.json +jq '.[].name' fruits.json + +#4.2. Accessing By Index +jq '.[1].price' fruits.json + +#4.3. Slicing +echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[6:9]' +echo '[1,2,3,4,5,6,7,8,9,10]' | jq '.[:6]' | jq '.[-2:]' + +#5.1. Getting Keys +jq '.fruit | keys' fruit.json + +#5.2. Returning the Length +jq '.fruit | length' fruit.json +jq '.fruit.name | length' fruit.json + +#5.3. Mapping Values +jq 'map(has("name"))' fruits.json +jq 'map(.price+2)' fruits.json + +#5.4. Min and Max +jq '[.[].price] | min' fruits.json +jq '[.[].price] | max' fruits.json + +#5.5. Selecting Values +jq '.[] | select(.price>0.5)' fruits.json +jq '.[] | select(.color=="yellow")' fruits.json +jq '.[] | select(.color=="yellow" and .price>=0.5)' fruits.json + +#5.6. Support For RegEx +jq '.[] | select(.name|test("^a.")) | .price' fruits.json + +#5.7. Find Unique Values +jq 'map(.color) | unique' fruits.json + +#5.8. Deleting Keys From JSON +jq 'del(.fruit.name)' fruit.json + +# 6. Transforming +jq '.query.pages | [.[] | map(.) | .[] | {page_title: .title, page_description: .extract}]' wikipedia.json diff --git a/linux-bash/json/src/main/bash/wikipedia.json b/linux-bash/json/src/main/bash/wikipedia.json new file mode 100644 index 0000000000..180b160bcc --- /dev/null +++ b/linux-bash/json/src/main/bash/wikipedia.json @@ -0,0 +1,22 @@ +{ + "query": { + "pages": [ + { + "21721040": { + "pageid": 21721040, + "ns": 0, + "title": "Stack Overflow", + "extract": "Some interesting text about Stack Overflow" + } + }, + { + "21721041": { + "pageid": 21721041, + "ns": 0, + "title": "Baeldung", + "extract": "A great place to learn about Java" + } + } + ] + } +} diff --git a/linux-bash/loops/README.md b/linux-bash/loops/README.md new file mode 100644 index 0000000000..8a0514f6f0 --- /dev/null +++ b/linux-bash/loops/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Linux Commands – Looping Through Directories](https://www.baeldung.com/linux/loop-directories) diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md new file mode 100644 index 0000000000..e0ee0c1600 --- /dev/null +++ b/linux-bash/text/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/remove-text-after-x-in-file) diff --git a/logging-modules/flogger/README.md b/logging-modules/flogger/README.md new file mode 100644 index 0000000000..ad7a25e24f --- /dev/null +++ b/logging-modules/flogger/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Flogger Fluent Logging](https://www.baeldung.com/flogger-logging) diff --git a/logging-modules/log4j2/README.md b/logging-modules/log4j2/README.md index dd326bc7a1..6a65ae9c02 100644 --- a/logging-modules/log4j2/README.md +++ b/logging-modules/log4j2/README.md @@ -5,3 +5,4 @@ - [Programmatic Configuration with Log4j 2](http://www.baeldung.com/log4j2-programmatic-config) - [Creating a Custom Log4j2 Appender](https://www.baeldung.com/log4j2-custom-appender) - [Get Log Output in JSON](http://www.baeldung.com/java-log-json-output) +- [System.out.println vs Loggers](https://www.baeldung.com/java-system-out-println-vs-loggers) diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java index 20366a229d..ae0eec727f 100644 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderIntegrationTest.java @@ -1,33 +1,40 @@ package com.baeldung.logback; import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; +import java.util.List; + +import static java.util.stream.Collectors.toList; +import static org.hamcrest.Matchers.hasItems; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; public class MapAppenderIntegrationTest { - private Logger rootLogger; + private Logger logger; @Before - public void setUp() throws Exception { - rootLogger = (Logger) LoggerFactory.getLogger("ROOT"); + public void setUp() { + logger = (Logger) LoggerFactory.getLogger(MapAppenderIntegrationTest.class); } @Test - public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception { - rootLogger.info("Test from {}", this.getClass().getSimpleName()); - MapAppender appender = (MapAppender) rootLogger.getAppender("map"); - assertEquals(appender.getEventMap().size(), 1); + public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() { + logger.info("Test from {}", this.getClass().getSimpleName()); + MapAppender appender = (MapAppender) logger.getAppender("map"); + + List messages = appender.getEventMap().values().stream().map(ILoggingEvent::getMessage).collect(toList()); + assertThat(messages, hasItems("Test from {}")); } @Test - public void givenNoPrefixSet_whenLoggerEmitsEvent_thenAppenderReceivesNoEvent() throws Exception { - rootLogger.info("Test from {}", this.getClass().getSimpleName()); - MapAppender appender = (MapAppender) rootLogger.getAppender("badMap"); + public void givenNoPrefixSet_whenLoggerEmitsEvent_thenAppenderReceivesNoEvent() { + logger.info("Test from {}", this.getClass().getSimpleName()); + MapAppender appender = (MapAppender) logger.getAppender("badMap"); assertEquals(appender.getEventMap().size(), 0); } - } diff --git a/logging-modules/logback/src/test/resources/logback-test.xml b/logging-modules/logback/src/test/resources/logback-test.xml index df81f18cc2..89c0124738 100644 --- a/logging-modules/logback/src/test/resources/logback-test.xml +++ b/logging-modules/logback/src/test/resources/logback-test.xml @@ -28,4 +28,9 @@ + + + + + \ No newline at end of file diff --git a/mapstruct/README.md b/mapstruct/README.md index be02c1186b..f5a1e1a092 100644 --- a/mapstruct/README.md +++ b/mapstruct/README.md @@ -5,4 +5,5 @@ This module contains articles about MapStruct. ###Relevant Articles: - [Quick Guide to MapStruct](https://www.baeldung.com/mapstruct) - [Custom Mapper with MapStruct](https://www.baeldung.com/mapstruct-custom-mapper) - +- [Using Multiple Source Objects with MapStruct](https://www.baeldung.com/mapstruct-multiple-source-objects) +- [Ignoring Unmapped Properties with MapStruct](https://www.baeldung.com/mapstruct-ignore-unmapped-properties) diff --git a/metrics/README.md b/metrics/README.md index b8a1bf026f..6050b2b310 100644 --- a/metrics/README.md +++ b/metrics/README.md @@ -8,4 +8,3 @@ This module contains articles about metrics. - [Introduction to Netflix Servo](https://www.baeldung.com/netflix-servo) - [Quick Guide to Micrometer](https://www.baeldung.com/micrometer) - [@Timed Annotation Using Metrics and AspectJ](https://www.baeldung.com/timed-metrics-aspectj) - diff --git a/micronaut/pom.xml b/micronaut/pom.xml index 2a8d135483..02ac36218d 100644 --- a/micronaut/pom.xml +++ b/micronaut/pom.xml @@ -1,136 +1,142 @@ - 4.0.0 - com.baeldung.micronaut - micronaut - 0.1 - micronaut + 4.0.0 + com.baeldung.micronaut + micronaut + 0.1 + micronaut - - - - io.micronaut - bom - ${micronaut.version} - pom - import - - - - - - io.micronaut - http-client - compile - - - io.micronaut - http-server-netty - compile - - - io.micronaut - inject - compile - - - io.micronaut - runtime - compile - - - javax.annotation - javax.annotation-api - 1.3.2 - compile - - - io.micronaut - inject-java - provided - - - ch.qos.logback - logback-classic - 1.2.3 - runtime - - - junit - junit - 4.12 - test - - - io.projectreactor - reactor-core - 3.1.6.RELEASE - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.1.0 - - - package - - shade - - - - - ${exec.mainClass} - - - - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - java - - -classpath - - ${exec.mainClass} - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - ${jdk.version} - ${jdk.version} - - -parameters - - - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.micronaut - inject-java + bom ${micronaut.version} - - - - - - - - - - com.baeldung.micronaut.helloworld.server.ServerApplication - 1.0.0.RC2 - 1.8 - + pom + import + + + + + + io.micronaut + http-client + compile + + + io.micronaut + http-server-netty + compile + + + io.micronaut + inject + compile + + + io.micronaut + runtime + compile + + + javax.annotation + javax.annotation-api + 1.3.2 + compile + + + io.micronaut + inject-java + provided + + + ch.qos.logback + logback-classic + 1.2.3 + runtime + + + junit + junit + 4.12 + test + + + io.projectreactor + reactor-core + 3.1.6.RELEASE + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + package + + shade + + + + + ${exec.mainClass} + + + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + java + + -classpath + + ${exec.mainClass} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + ${jdk.version} + ${jdk.version} + + -parameters + + + + io.micronaut + inject-java + ${micronaut.version} + + + + + + + + + + com.baeldung.micronaut.helloworld.server.ServerApplication + 1.0.0.RC2 + 1.8 + diff --git a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientUnitTest.java similarity index 95% rename from micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java rename to micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientUnitTest.java index c8c1d6b12a..336374d5a6 100644 --- a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientTest.java +++ b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClientUnitTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class ConcreteGreetingClientTest +public class ConcreteGreetingClientUnitTest { private EmbeddedServer server; private ConcreteGreetingClient client; diff --git a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientUnitTest.java similarity index 94% rename from micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java rename to micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientUnitTest.java index 0f2ca460ac..c47fb3a31d 100644 --- a/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientTest.java +++ b/micronaut/src/test/java/com/baeldung/micronaut/helloworld/client/GreetingClientUnitTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class GreetingClientTest { +public class GreetingClientUnitTest { private EmbeddedServer server; private GreetingClient client; diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index edc115d186..fe272b56a3 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -78,6 +78,6 @@ 3.3.0 1.0.22.RELEASE - 2.1.7.RELEASE + 2.1.9.RELEASE diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index bda5fb70e7..84844dbb8b 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -1,6 +1,6 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 parent-kotlin parent-kotlin @@ -13,34 +13,34 @@ 1.0.0-SNAPSHOT - - - jcenter - http://jcenter.bintray.com - - - kotlin-ktor - https://dl.bintray.com/kotlin/ktor/ - - - kotlin-eap - http://dl.bintray.com/kotlin/kotlin-eap - - - spring-milestone - Spring Milestone Repository - http://repo.spring.io/milestone - - - - - - kotlin-eap - http://dl.bintray.com/kotlin/kotlin-eap - - - - + + + jcenter + http://jcenter.bintray.com + + + kotlin-ktor + https://dl.bintray.com/kotlin/ktor/ + + + kotlin-eap + http://dl.bintray.com/kotlin/kotlin-eap + + + spring-milestone + Spring Milestone Repository + http://repo.spring.io/milestone + + + + + + kotlin-eap + http://dl.bintray.com/kotlin/kotlin-eap + + + + org.springframework.boot @@ -56,15 +56,15 @@ org.jetbrains.kotlin kotlin-stdlib-jdk8 - - - org.jetbrains.kotlin - kotlin-stdlib - + + + org.jetbrains.kotlin + kotlin-stdlib + org.jetbrains.kotlin kotlin-reflect - + org.jetbrains.kotlinx @@ -113,9 +113,9 @@ ${project.basedir}/src/main/java ${java.version} - - -Xjvm-default=enable - + + -Xjvm-default=enable + diff --git a/patterns/design-patterns-creational/README.md b/patterns/design-patterns-creational/README.md index 99b9b39787..026115a6d6 100644 --- a/patterns/design-patterns-creational/README.md +++ b/patterns/design-patterns-creational/README.md @@ -6,4 +6,5 @@ - [Double-Checked Locking with Singleton](https://www.baeldung.com/java-singleton-double-checked-locking) - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [Automatic Generation of the Builder Pattern with FreeBuilder](https://www.baeldung.com/java-builder-pattern-freebuilder) -- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements) \ No newline at end of file +- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements) +- [Prototype Pattern in Java](https://www.baeldung.com/java-pattern-prototype) diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 3271f0c1b6..5bbdeecbea 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -8,3 +8,4 @@ This module contains articles about Object-relational Mapping (ORM) with Hiberna - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) - [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) - [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) +- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) diff --git a/persistence-modules/hibernate-parameters/pom.xml b/persistence-modules/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/resources/META-INF/persistence.xml b/persistence-modules/java-jpa-2/src/main/resources/META-INF/persistence.xml index cd46901792..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 @@ -135,4 +135,32 @@ + + org.hibernate.jpa.HibernatePersistenceProvider + 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 + + + + + + + + + + + + + \ 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/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/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 161e60c2cb..ab7fb65e44 100644 --- a/persistence-modules/sirix/README.md +++ b/persistence-modules/sirix/README.md @@ -2,4 +2,3 @@ - [Introduction to Sirix](https://www.baeldung.com/introduction-to-sirix) - [A Guide to SirixDB](https://www.baeldung.com/sirix) - diff --git a/persistence-modules/spring-boot-jdbi/README.md b/persistence-modules/spring-boot-jdbi/README.md new file mode 100644 index 0000000000..5d171fb2ca --- /dev/null +++ b/persistence-modules/spring-boot-jdbi/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Using JDBI with Spring Boot](https://www.baeldung.com/spring-boot-jdbi) diff --git a/persistence-modules/spring-boot-persistence-h2/pom.xml b/persistence-modules/spring-boot-persistence-h2/pom.xml index bd36a46144..30c727bfc8 100644 --- a/persistence-modules/spring-boot-persistence-h2/pom.xml +++ b/persistence-modules/spring-boot-persistence-h2/pom.xml @@ -26,11 +26,6 @@ com.h2database h2 - - org.springframework.boot - spring-boot-starter-test - test - diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index c7cda07a1a..3ad925f16b 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -17,14 +17,17 @@ org.springframework.boot spring-boot-starter-web + ${spring-boot.version} org.springframework.boot spring-boot-starter-thymeleaf + ${spring-boot.version} org.springframework.boot spring-boot-starter-data-jpa + ${spring-boot.version} com.zaxxer @@ -35,6 +38,7 @@ org.springframework.boot spring-boot-starter-test + ${spring-boot.version} org.mockito @@ -99,6 +103,7 @@ 2.0.1.Final 10.13.1.1 2.3.4 + 2.1.7.RELEASE diff --git a/persistence-modules/spring-data-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/java-strings-ops/src/main/resources/logback.xml b/persistence-modules/spring-data-geode/src/main/resources/logback.xml similarity index 100% rename from java-strings-ops/src/main/resources/logback.xml rename to persistence-modules/spring-data-geode/src/main/resources/logback.xml 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..32f81d5745 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/pom.xml @@ -0,0 +1,70 @@ + + + + 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-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + ${h2.version} + + + + + 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.4.200 + + + 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/model/Payment.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/Payment.java new file mode 100644 index 0000000000..2c24e5777e --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/Payment.java @@ -0,0 +1,55 @@ +package com.baeldung.model; + +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/main/java/com/baeldung/model/User.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/User.java new file mode 100644 index 0000000000..94d0c023f2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/User.java @@ -0,0 +1,42 @@ +package com.baeldung.model; + +import javax.persistence.*; +import java.util.Set; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Long id; + + private String username; + + @ElementCollection + private Set permissions; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Set getPermissions() { + return permissions; + } + + public void setPermissions(Set permissions) { + this.permissions = permissions; + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java new file mode 100644 index 0000000000..bb3ce781f6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.repository; + +import com.baeldung.model.User; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + + @EntityGraph(attributePaths = "permissions") + Optional findDetailedByUsername(String username); + + Optional findSummaryByUsername(String username); + + Optional findByUsername(String username); +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/SimpleUserService.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/SimpleUserService.java new file mode 100644 index 0000000000..6782254f61 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/SimpleUserService.java @@ -0,0 +1,24 @@ +package com.baeldung.service; + +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Service +public class SimpleUserService implements UserService { + + private final UserRepository userRepository; + + public SimpleUserService(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + @Transactional(readOnly = true) + public Optional findOne(String username) { + return userRepository.findDetailedByUsername(username); + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/UserService.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/UserService.java new file mode 100644 index 0000000000..11b3dc82ce --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/service/UserService.java @@ -0,0 +1,9 @@ +package com.baeldung.service; + +import com.baeldung.model.User; + +import java.util.Optional; + +public interface UserService { + Optional findOne(String username); +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/DetailedUserDto.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/DetailedUserDto.java new file mode 100644 index 0000000000..0d8fe02b91 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/DetailedUserDto.java @@ -0,0 +1,45 @@ +package com.baeldung.web; + +import com.baeldung.model.User; + +import java.util.Set; + +public class DetailedUserDto { + + private Long id; + private String username; + private Set permissions; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Set getPermissions() { + return permissions; + } + + public void setPermissions(Set permissions) { + this.permissions = permissions; + } + + public static DetailedUserDto fromEntity(User user) { + DetailedUserDto detailed = new DetailedUserDto(); + detailed.setId(user.getId()); + detailed.setUsername(user.getUsername()); + detailed.setPermissions(user.getPermissions()); + + return detailed; + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/UserController.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/UserController.java new file mode 100644 index 0000000000..867d60cc2f --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/web/UserController.java @@ -0,0 +1,27 @@ +package com.baeldung.web; + +import com.baeldung.service.UserService; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/users") +public class UserController { + + private final UserService userService; + + public UserController(UserService userService) { + this.userService = userService; + } + + @GetMapping("/{username}") + public ResponseEntity findOne(@PathVariable String username) { + return userService.findOne(username) + .map(DetailedUserDto::fromEntity) + .map(ResponseEntity::ok) + .orElse(ResponseEntity.notFound().build()); + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java new file mode 100644 index 0000000000..ba94fc111b --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java @@ -0,0 +1,54 @@ +package com.baeldung.osiv; + +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Arrays; +import java.util.HashSet; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class UserControllerIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private MockMvc mockMvc; + + @BeforeEach + void setUp() { + User user = new User(); + user.setUsername("root"); + user.setPermissions(new HashSet<>(Arrays.asList("PERM_READ", "PERM_WRITE"))); + + userRepository.save(user); + } + + @Test + void givenTheUserExists_WhenOsivIsEnabled_ThenLazyInitWorkEverywhere() throws Exception { + mockMvc.perform(get("/users/root")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value("root")) + .andExpect(jsonPath("$.permissions", containsInAnyOrder("PERM_READ", "PERM_WRITE"))); + } + + @AfterEach + void flushDb() { + userRepository.deleteAll(); + } +} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java new file mode 100644 index 0000000000..1ce8e91ec5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java @@ -0,0 +1,152 @@ +package com.baeldung.tx; + +import com.baeldung.model.Payment; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.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 javax.persistence.EntityManager; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; + +@DataJpaTest +@ActiveProfiles("test") +@Transactional(propagation = NOT_SUPPORTED) +class ManualTransactionIntegrationTest { + + @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); + } + +} 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..f9497c8f37 --- /dev/null +++ b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties @@ -0,0 +1,2 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 4ae8ac0a87..cd8c729844 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -87,7 +87,8 @@ ${maven-surefire-plugin.version} true - true + false + 0 -Xmx1024m diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java index 1333f94653..af790c99b7 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java @@ -38,7 +38,7 @@ public class RedisKeyCommandsIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java index 88c4fa6eed..58846d7c27 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java @@ -36,7 +36,7 @@ public class RedisTemplateListOpsIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java index afa5267582..5d12f90f34 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java @@ -38,7 +38,7 @@ public class RedisTemplateValueOpsIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 1c69b63c09..6f9e6a8757 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -33,7 +33,7 @@ public class RedisMessageListenerIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } @@ -46,7 +46,7 @@ public class RedisMessageListenerIntegrationTest { public void testOnMessage() throws Exception { String message = "Message " + UUID.randomUUID(); redisMessagePublisher.publish(message); - Thread.sleep(100); + Thread.sleep(1000); assertTrue(RedisMessageSubscriber.messageList.get(0).contains(message)); } } \ No newline at end of file diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index b1a36475c3..24191a42b9 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -34,7 +34,7 @@ public class StudentRepositoryIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 128M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java index e093892365..f5c8177cbe 100644 --- a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,16 +1,35 @@ package org.baeldung; +import com.baeldung.spring.data.redis.config.RedisConfig; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import redis.embedded.RedisServerBuilder; -import com.baeldung.spring.data.redis.config.RedisConfig; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; @RunWith(SpringJUnit4ClassRunner.class) +@DirtiesContext(classMode = BEFORE_CLASS) @ContextConfiguration(classes = RedisConfig.class) public class SpringContextIntegrationTest { + private static redis.embedded.RedisServer redisServer; + + @BeforeClass + public static void startRedisServer() { + redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() { + redisServer.stop(); + } + @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index d04e9f6f41..489d990fc3 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -13,6 +13,7 @@ - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) +- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource/) ### Eclipse Config diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index 8e55a59c7c..db0d0ce83c 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -12,6 +12,7 @@ - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) - [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) +- [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/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 5404c908d3..88aa7011d0 100644 --- a/pom.xml +++ b/pom.xml @@ -381,7 +381,7 @@ cloud-foundry-uaa/cf-uaa-oauth2-client cloud-foundry-uaa/cf-uaa-oauth2-resource-server code-generation - core-groovy + core-groovy core-groovy-2 core-groovy-collections @@ -391,10 +391,19 @@ 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 @@ -431,7 +440,12 @@ core-java-modules/core-java-sun core-java-modules/core-java-string-conversions core-java-modules/core-java-string-conversions-2 + core-java-modules/core-java-string-operations + core-java-modules/core-java-string-operations-2 + core-java-modules/core-java-string-algorithms + core-java-modules/core-java-string-algorithms-2 core-java-modules/core-java-string-apis + core-java-modules/core-java-strings core-java-modules/core-java core-java-modules/core-java-jvm core-scala @@ -482,6 +496,7 @@ jackson-2 jackson-simple java-collections-conversions + java-collections-conversions-2 java-collections-maps java-collections-maps-2 java-jdi @@ -493,12 +508,6 @@ java-numbers-2 java-rmi java-spi - java-streams - - java-strings - java-strings-2 - java-strings-3 - java-strings-ops java-vavr-stream java-websocket javafx @@ -532,6 +541,7 @@ libraries libraries-2 + libraries-3 libraries-data libraries-data-2 libraries-data-db @@ -592,8 +602,10 @@ rule-engines rsocket - rxjava - rxjava-2 + rxjava-core + rxjava-observables + rxjava-operators + rxjava-libraries software-security/sql-injection-samples tensorflow-java @@ -609,7 +621,7 @@ spring-boot-nashorn java-blockchain -wildfly + wildfly @@ -1145,7 +1157,7 @@ cloud-foundry-uaa/cf-uaa-oauth2-client cloud-foundry-uaa/cf-uaa-oauth2-resource-server code-generation - core-groovy + core-groovy core-groovy-2 core-groovy-collections @@ -1154,10 +1166,19 @@ 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 @@ -1191,9 +1212,14 @@ core-java-modules/core-java-perf core-java-modules/core-java-sun core-java-modules/core-java-string-conversions - core-java-modules/core-java-string-conversions-2 - core-java-modules/core-java-string-apis - core-scala + core-java-modules/core-java-string-conversions-2 + core-java-modules/core-java-string-operations + core-java-modules/core-java-string-operations-2 + core-java-modules/core-java-string-algorithms + core-java-modules/core-java-string-algorithms-2 + core-java-modules/core-java-string-apis + core-java-modules/core-java-strings + core-scala couchbase custom-pmd @@ -1241,6 +1267,7 @@ jackson-2 jackson-simple java-collections-conversions + java-collections-conversions-2 java-collections-maps java-collections-maps-2 java-jdi @@ -1252,12 +1279,6 @@ java-numbers-2 java-rmi java-spi - java-streams - - java-strings - java-strings-2 - java-strings-3 - java-strings-ops java-vavr-stream java-websocket javafx @@ -1289,6 +1310,7 @@ libraries + libraries-3 libraries-data libraries-data-2 libraries-data-db @@ -1347,8 +1369,10 @@ rule-engines rsocket - rxjava - rxjava-2 + rxjava-core + rxjava-observables + rxjava-operators + rxjava-libraries oauth2-framework-impl spf4j spring-boot-performance diff --git a/quarkus/pom.xml b/quarkus/pom.xml index 5190d0932a..31e3c8f8a0 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -1,115 +1,121 @@ - 4.0.0 - com.baeldung.quarkus - quarkus - 1.0-SNAPSHOT - quarkus - - - 2.22.0 - 0.15.0 - 1.8 - UTF-8 - 1.8 - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + 4.0.0 + com.baeldung.quarkus + quarkus + 1.0-SNAPSHOT + quarkus + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 2.22.0 + 0.15.0 + 1.8 + UTF-8 + 1.8 + + + + + io.quarkus + quarkus-bom + ${quarkus.version} + pom + import + + + - - io.quarkus - quarkus-bom - ${quarkus.version} - pom - import - - - - - - io.quarkus - quarkus-resteasy - - - io.quarkus - quarkus-junit5 - test - - - io.rest-assured - rest-assured - test - - - - - - io.quarkus - quarkus-maven-plugin - ${quarkus.version} - - - - build - - - - - - maven-surefire-plugin - ${surefire-plugin.version} - - - org.jboss.logmanager.LogManager - - - - - - - - native - - - native - - - - - + io.quarkus - quarkus-maven-plugin - ${quarkus.version} - - - - native-image - + quarkus-resteasy + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + io.quarkus + quarkus-maven-plugin + ${quarkus.version} + + + + build + + + + + + maven-surefire-plugin + ${surefire-plugin.version} - true + + org.jboss.logmanager.LogManager + - - - - - maven-failsafe-plugin - ${surefire-plugin.version} - - - - integration-test - verify - - - - ${project.build.directory}/${project.build.finalName}-runner - - - - - + - - - + + + + native + + + native + + + + + + io.quarkus + quarkus-maven-plugin + ${quarkus.version} + + + + native-image + + + true + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + + + + + + + + + diff --git a/rxjava-2/README.md b/rxjava-2/README.md deleted file mode 100644 index 87f606a323..0000000000 --- a/rxjava-2/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## RxJava - -This module contains articles about RxJava. - -### Relevant articles: - -- [RxJava and Error Handling](https://www.baeldung.com/rxjava-error-handling) -- [RxJava 2 – Flowable](https://www.baeldung.com/rxjava-2-flowable) -- [RxJava Maybe](https://www.baeldung.com/rxjava-maybe) -- [Introduction to RxRelay for RxJava](https://www.baeldung.com/rx-relay) -- [Combining RxJava Completables](https://www.baeldung.com/rxjava-completable) -- [Converting Synchronous and Asynchronous APIs to Observables using RxJava2](https://www.baeldung.com/rxjava-apis-to-observables) -- [RxJava Hooks](https://www.baeldung.com/rxjava-hooks) -- More articles: [[<-- prev]](/rxjava) diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml deleted file mode 100644 index 47d16ec8dd..0000000000 --- a/rxjava-2/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - rxjava-2 - rxjava-2 - 1.0-SNAPSHOT - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - io.reactivex.rxjava2 - rxjava - ${rx.java2.version} - - - com.jayway.awaitility - awaitility - ${awaitility.version} - - - org.assertj - assertj-core - ${assertj.version} - - - com.jakewharton.rxrelay2 - rxrelay - ${rxrelay.version} - - - - com.github.akarnokd - rxjava2-extensions - ${rxjava2.ext.version} - - - - - 3.8.0 - 2.2.2 - 1.7.0 - 2.0.0 - 0.20.4 - - \ No newline at end of file diff --git a/rxjava-2/src/main/resources/logback.xml b/rxjava-2/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/rxjava-2/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/rxjava-core/README.md b/rxjava-core/README.md new file mode 100644 index 0000000000..2773bd9423 --- /dev/null +++ b/rxjava-core/README.md @@ -0,0 +1,16 @@ +## RxJava + +This module contains articles about RxJava. + +### Relevant articles: + +- [Dealing with Backpressure with RxJava](https://www.baeldung.com/rxjava-backpressure) +- [How to Test RxJava?](https://www.baeldung.com/rxjava-testing) +- [Introduction to RxJava](https://www.baeldung.com/rx-java) +- [Schedulers in RxJava](https://www.baeldung.com/rxjava-schedulers) +- [Difference Between Flatmap and Switchmap in RxJava](https://www.baeldung.com/rxjava-flatmap-switchmap) +- [RxJava and Error Handling](https://www.baeldung.com/rxjava-error-handling) +- [RxJava Maybe](https://www.baeldung.com/rxjava-maybe) +- [Combining RxJava Completables](https://www.baeldung.com/rxjava-completable) +- [RxJava Hooks](https://www.baeldung.com/rxjava-hooks) +- More articles: [[next -->]](/rxjava-2) diff --git a/rxjava-core/pom.xml b/rxjava-core/pom.xml new file mode 100644 index 0000000000..401ad83808 --- /dev/null +++ b/rxjava-core/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + rxjava-core + 1.0-SNAPSHOT + rxjava-core + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex + rxjava + ${rx.java.version} + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + + org.assertj + assertj-core + ${assertj.version} + + + + + 3.8.0 + 1.2.5 + 1.7.0 + 2.2.2 + + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ComputeFunction.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ComputeFunction.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ComputeFunction.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ComputeFunction.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ConnectableObservableImpl.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ObservableImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ObservableImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ObservableImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ObservableImpl.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/ResourceManagement.java b/rxjava-core/src/main/java/com/baeldung/rxjava/ResourceManagement.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/ResourceManagement.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/ResourceManagement.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/SingleImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/SingleImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/SingleImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/SingleImpl.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/SubjectImpl.java b/rxjava-core/src/main/java/com/baeldung/rxjava/SubjectImpl.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/SubjectImpl.java rename to rxjava-core/src/main/java/com/baeldung/rxjava/SubjectImpl.java diff --git a/java-strings/src/main/resources/logback.xml b/rxjava-core/src/main/resources/logback.xml similarity index 100% rename from java-strings/src/main/resources/logback.xml rename to rxjava-core/src/main/resources/logback.xml diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java similarity index 96% rename from rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java index b79fa9af22..f71d9e8839 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java +++ b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksManualTest.java @@ -1,84 +1,84 @@ -package com.baeldung.rxjava; - -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Test; - -import io.reactivex.Observable; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; - -public class RxJavaHooksManualTest { - - private boolean initHookCalled = false; - private boolean hookCalled = false; - - @Test - public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.io()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @Test - public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { - - RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 15) - .map(v -> v * 2) - .subscribeOn(Schedulers.newThread()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @Test - public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - - RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.single()) - .test(); - assertTrue(hookCalled && initHookCalled); - - } - - @After - public void reset() { - hookCalled = false; - initHookCalled = false; - RxJavaPlugins.reset(); - } -} +package com.baeldung.rxjava; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import io.reactivex.Observable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksManualTest { + + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setIoSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.io()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() { + + RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 15) + .map(v -> v * 2) + .subscribeOn(Schedulers.newThread()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @Test + public void givenSingleScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitSingleSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + + RxJavaPlugins.setSingleSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + assertTrue(hookCalled && initHookCalled); + + } + + @After + public void reset() { + hookCalled = false; + initHookCalled = false; + RxJavaPlugins.reset(); + } +} diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java similarity index 96% rename from rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java index dd4287a4a9..cea6cc70f6 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java +++ b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaHooksUnitTest.java @@ -1,244 +1,244 @@ -package com.baeldung.rxjava; - -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Test; - -import io.reactivex.Completable; -import io.reactivex.Flowable; -import io.reactivex.Maybe; -import io.reactivex.Observable; -import io.reactivex.Single; -import io.reactivex.flowables.ConnectableFlowable; -import io.reactivex.observables.ConnectableObservable; -import io.reactivex.plugins.RxJavaPlugins; -import io.reactivex.schedulers.Schedulers; - -public class RxJavaHooksUnitTest { - - private boolean initHookCalled = false; - private boolean hookCalled = false; - - @Test - public void givenObservable_whenError_shouldExecuteTheHook() { - RxJavaPlugins.setErrorHandler(throwable -> { - hookCalled = true; - }); - - Observable.error(new IllegalStateException()) - .subscribe(); - assertTrue(hookCalled); - } - - @Test - public void givenCompletable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnCompletableAssembly(completable -> { - hookCalled = true; - return completable; - }); - Completable.fromSingle(Single.just(1)); - assertTrue(hookCalled); - } - - @Test - public void givenCompletable_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { - hookCalled = true; - return observer; - }); - - Completable.fromSingle(Single.just(1)) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenObservable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnObservableAssembly(observable -> { - hookCalled = true; - return observable; - }); - - Observable.range(1, 10); - assertTrue(hookCalled); - } - - @Test - public void givenObservable_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { - hookCalled = true; - return observer; - }); - - Observable.range(1, 10) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenConnectableObservable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { - hookCalled = true; - return connectableObservable; - }); - - ConnectableObservable.range(1, 10) - .publish() - .connect(); - assertTrue(hookCalled); - } - - @Test - public void givenFlowable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnFlowableAssembly(flowable -> { - hookCalled = true; - return flowable; - }); - - Flowable.range(1, 10); - assertTrue(hookCalled); - } - - @Test - public void givenFlowable_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { - hookCalled = true; - return observer; - }); - - Flowable.range(1, 10) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { - hookCalled = true; - return connectableFlowable; - }); - - ConnectableFlowable.range(1, 10) - .publish() - .connect(); - assertTrue(hookCalled); - } - - @Test - public void givenParallel_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { - hookCalled = true; - return parallelFlowable; - }); - - Flowable.range(1, 10) - .parallel(); - assertTrue(hookCalled); - } - - @Test - public void givenMaybe_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnMaybeAssembly(maybe -> { - hookCalled = true; - return maybe; - }); - - Maybe.just(1); - assertTrue(hookCalled); - } - - @Test - public void givenMaybe_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { - hookCalled = true; - return observer; - }); - - Maybe.just(1) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenSingle_whenAssembled_shouldExecuteTheHook() { - - RxJavaPlugins.setOnSingleAssembly(single -> { - hookCalled = true; - return single; - }); - - Single.just(1); - assertTrue(hookCalled); - } - - @Test - public void givenSingle_whenSubscribed_shouldExecuteTheHook() { - - RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { - hookCalled = true; - return observer; - }); - - Single.just(1) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() { - - RxJavaPlugins.setScheduleHandler((runnable) -> { - hookCalled = true; - return runnable; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.single()) - .test(); - hookCalled = false; - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.computation()) - .test(); - assertTrue(hookCalled); - } - - @Test - public void givenComputationScheduler_whenCalled_shouldExecuteTheHooks() { - - RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { - initHookCalled = true; - return scheduler.call(); - }); - RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { - hookCalled = true; - return scheduler; - }); - - Observable.range(1, 10) - .map(v -> v * 2) - .subscribeOn(Schedulers.computation()) - .test(); - assertTrue(hookCalled && initHookCalled); - } - - @After - public void reset() { - initHookCalled = false; - hookCalled = false; - RxJavaPlugins.reset(); - } -} +package com.baeldung.rxjava; + +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Test; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Maybe; +import io.reactivex.Observable; +import io.reactivex.Single; +import io.reactivex.flowables.ConnectableFlowable; +import io.reactivex.observables.ConnectableObservable; +import io.reactivex.plugins.RxJavaPlugins; +import io.reactivex.schedulers.Schedulers; + +public class RxJavaHooksUnitTest { + + private boolean initHookCalled = false; + private boolean hookCalled = false; + + @Test + public void givenObservable_whenError_shouldExecuteTheHook() { + RxJavaPlugins.setErrorHandler(throwable -> { + hookCalled = true; + }); + + Observable.error(new IllegalStateException()) + .subscribe(); + assertTrue(hookCalled); + } + + @Test + public void givenCompletable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnCompletableAssembly(completable -> { + hookCalled = true; + return completable; + }); + Completable.fromSingle(Single.just(1)); + assertTrue(hookCalled); + } + + @Test + public void givenCompletable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnCompletableSubscribe((completable, observer) -> { + hookCalled = true; + return observer; + }); + + Completable.fromSingle(Single.just(1)) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenObservable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnObservableAssembly(observable -> { + hookCalled = true; + return observable; + }); + + Observable.range(1, 10); + assertTrue(hookCalled); + } + + @Test + public void givenObservable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnObservableSubscribe((observable, observer) -> { + hookCalled = true; + return observer; + }); + + Observable.range(1, 10) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenConnectableObservable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnConnectableObservableAssembly(connectableObservable -> { + hookCalled = true; + return connectableObservable; + }); + + ConnectableObservable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); + } + + @Test + public void givenFlowable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnFlowableAssembly(flowable -> { + hookCalled = true; + return flowable; + }); + + Flowable.range(1, 10); + assertTrue(hookCalled); + } + + @Test + public void givenFlowable_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnFlowableSubscribe((flowable, observer) -> { + hookCalled = true; + return observer; + }); + + Flowable.range(1, 10) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> { + hookCalled = true; + return connectableFlowable; + }); + + ConnectableFlowable.range(1, 10) + .publish() + .connect(); + assertTrue(hookCalled); + } + + @Test + public void givenParallel_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnParallelAssembly(parallelFlowable -> { + hookCalled = true; + return parallelFlowable; + }); + + Flowable.range(1, 10) + .parallel(); + assertTrue(hookCalled); + } + + @Test + public void givenMaybe_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnMaybeAssembly(maybe -> { + hookCalled = true; + return maybe; + }); + + Maybe.just(1); + assertTrue(hookCalled); + } + + @Test + public void givenMaybe_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnMaybeSubscribe((maybe, observer) -> { + hookCalled = true; + return observer; + }); + + Maybe.just(1) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenSingle_whenAssembled_shouldExecuteTheHook() { + + RxJavaPlugins.setOnSingleAssembly(single -> { + hookCalled = true; + return single; + }); + + Single.just(1); + assertTrue(hookCalled); + } + + @Test + public void givenSingle_whenSubscribed_shouldExecuteTheHook() { + + RxJavaPlugins.setOnSingleSubscribe((single, observer) -> { + hookCalled = true; + return observer; + }); + + Single.just(1) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() { + + RxJavaPlugins.setScheduleHandler((runnable) -> { + hookCalled = true; + return runnable; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.single()) + .test(); + hookCalled = false; + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled); + } + + @Test + public void givenComputationScheduler_whenCalled_shouldExecuteTheHooks() { + + RxJavaPlugins.setInitComputationSchedulerHandler((scheduler) -> { + initHookCalled = true; + return scheduler.call(); + }); + RxJavaPlugins.setComputationSchedulerHandler((scheduler) -> { + hookCalled = true; + return scheduler; + }); + + Observable.range(1, 10) + .map(v -> v * 2) + .subscribeOn(Schedulers.computation()) + .test(); + assertTrue(hookCalled && initHookCalled); + } + + @After + public void reset() { + initHookCalled = false; + hookCalled = false; + RxJavaPlugins.reset(); + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/RxJavaUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/SchedulersLiveTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/SingleUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/SingleUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java b/rxjava-core/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java rename to rxjava-core/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java diff --git a/rxjava-libraries/README.md b/rxjava-libraries/README.md new file mode 100644 index 0000000000..ac8aac6908 --- /dev/null +++ b/rxjava-libraries/README.md @@ -0,0 +1,10 @@ +## RxJava Libraries + + This module contains articles about RxJava libraries + +### Related Articles: + +- [RxJava 2 – Flowable](https://www.baeldung.com/rxjava-2-flowable) +- [Introduction to RxRelay for RxJava](https://www.baeldung.com/rx-relay) +- [Introduction to rxjava-jdbc](https://www.baeldung.com/rxjava-jdbc) + diff --git a/rxjava-libraries/pom.xml b/rxjava-libraries/pom.xml new file mode 100644 index 0000000000..541d9116c8 --- /dev/null +++ b/rxjava-libraries/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + rxjava-libraries + 1.0-SNAPSHOT + rxjava-libraries + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex + rxjava + ${rx.java.version} + + + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} + + + com.jakewharton.rxrelay2 + rxrelay + ${rxrelay.version} + + + com.github.davidmoten + rxjava-jdbc + ${rx.java.jdbc.version} + + + com.h2database + h2 + ${h2.version} + runtime + + + org.assertj + assertj-core + ${assertj.version} + + + + + + 0.7.11 + 1.2.5 + 2.0.0 + 2.2.2 + 3.8.0 + + + \ No newline at end of file diff --git a/rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/RandomRelay.java similarity index 100% rename from rxjava-2/src/main/java/com/baeldung/rxjava/RandomRelay.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/RandomRelay.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Connector.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Connector.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Connector.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Connector.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Employee.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Employee.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Employee.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Employee.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Manager.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Manager.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Manager.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Manager.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/jdbc/Utils.java b/rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Utils.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/jdbc/Utils.java rename to rxjava-libraries/src/main/java/com/baeldung/rxjava/jdbc/Utils.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapClassIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertBlobIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java b/rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java rename to rxjava-libraries/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java diff --git a/rxjava/src/test/resources/actual_clob b/rxjava-libraries/src/test/resources/actual_clob similarity index 100% rename from rxjava/src/test/resources/actual_clob rename to rxjava-libraries/src/test/resources/actual_clob diff --git a/rxjava/src/test/resources/expected_clob b/rxjava-libraries/src/test/resources/expected_clob similarity index 100% rename from rxjava/src/test/resources/expected_clob rename to rxjava-libraries/src/test/resources/expected_clob diff --git a/rxjava-observables/README.md b/rxjava-observables/README.md new file mode 100644 index 0000000000..3bec990012 --- /dev/null +++ b/rxjava-observables/README.md @@ -0,0 +1,11 @@ +## RxJava Observables + + This module contains articles about RxJava Observables + +### Related Articles: + +- [Combining Observables in RxJava](https://www.baeldung.com/rxjava-combine-observables) +- [RxJava One Observable, Multiple Subscribers](https://www.baeldung.com/rxjava-multiple-subscribers-observable) +- [RxJava StringObservable](https://www.baeldung.com/rxjava-string) +- [Filtering Observables in RxJava](https://www.baeldung.com/rxjava-filtering) + diff --git a/rxjava-observables/pom.xml b/rxjava-observables/pom.xml new file mode 100644 index 0000000000..c2bf0bcd88 --- /dev/null +++ b/rxjava-observables/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + rxjava-observables + 1.0-SNAPSHOT + rxjava-observables + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.reactivex + rxjava + ${rx.java.version} + + + io.reactivex + rxjava-string + ${rx.java.string.version} + + + org.assertj + assertj-core + ${assertj.version} + + + + + + 1.1.1 + 1.2.5 + 3.8.0 + + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java b/rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java rename to rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersColdObs.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java b/rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java rename to rxjava-observables/src/main/java/com/baeldung/rxjava/MultipleSubscribersHotObs.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/combine/ObservableCombineUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java b/rxjava-observables/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java rename to rxjava-observables/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java diff --git a/rxjava-operators/README.md b/rxjava-operators/README.md new file mode 100644 index 0000000000..293d310bbd --- /dev/null +++ b/rxjava-operators/README.md @@ -0,0 +1,12 @@ +## RxJava Operators + + This module contains articles about RxJava Operators + +### Related Articles: + +- [Mathematical and Aggregate Operators in RxJava](https://www.baeldung.com/rxjava-math) +- [Observable Utility Operators in RxJava](https://www.baeldung.com/rxjava-observable-operators) +- [Implementing Custom Operators in RxJava](https://www.baeldung.com/rxjava-custom-operators) +- [Converting Synchronous and Asynchronous APIs to Observables using RxJava2](https://www.baeldung.com/rxjava-apis-to-observables) + + diff --git a/rxjava/pom.xml b/rxjava-operators/pom.xml similarity index 66% rename from rxjava/pom.xml rename to rxjava-operators/pom.xml index 85106d1127..8064613f45 100644 --- a/rxjava/pom.xml +++ b/rxjava-operators/pom.xml @@ -1,11 +1,11 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - rxjava + rxjava-operators 1.0-SNAPSHOT - rxjava - + rxjava-operators + com.baeldung parent-java @@ -19,48 +19,40 @@ rxjava ${rx.java.version} - - io.reactivex - rxjava-math - ${rx.java.math.version} + io.reactivex.rxjava2 + rxjava + ${rx.java2.version} - + - io.reactivex - rxjava-string - ${rx.java.string.version} - - - - com.jayway.awaitility - awaitility - ${awaitility.version} - - - com.github.davidmoten - rxjava-jdbc - ${rx.java.jdbc.version} - - - com.h2database - h2 - ${h2.version} - runtime + com.github.akarnokd + rxjava2-extensions + ${rxjava2.ext.version} org.assertj assertj-core ${assertj.version} + + io.reactivex + rxjava-math + ${rx.java.math.version} + + + com.jayway.awaitility + awaitility + ${awaitility.version} + + 0.20.4 + 2.2.2 3.8.0 1.2.5 - 0.7.11 1.0.0 - 1.1.1 1.7.0 diff --git a/rxjava/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java b/rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java rename to rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToCleanString.java diff --git a/rxjava/src/main/java/com/baeldung/rxjava/operator/ToLength.java b/rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToLength.java similarity index 100% rename from rxjava/src/main/java/com/baeldung/rxjava/operator/ToLength.java rename to rxjava-operators/src/main/java/com/baeldung/rxjava/operator/ToLength.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java similarity index 96% rename from rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java index 90f4fe94ae..2842fab80e 100644 --- a/rxjava-2/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java +++ b/rxjava-operators/src/test/java/com/baeldung/rxjava/AsyncAndSyncToObservableIntegrationTest.java @@ -1,107 +1,107 @@ -package com.baeldung.rxjava; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.junit.Test; - -import hu.akarnokd.rxjava2.async.AsyncObservable; -import io.reactivex.Observable; - -public class AsyncAndSyncToObservableIntegrationTest { - - AtomicInteger counter = new AtomicInteger(); - Callable callable = () -> counter.incrementAndGet(); - - /* Method will execute every time it gets subscribed*/ - @Test - public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() { - - Observable source = Observable.fromCallable(callable); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(i); - - assertEquals(i, counter.get()); - } - } - - /* Method will execute only once and cache its result.*/ - @Test - public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() { - - Observable source = AsyncObservable.start(callable); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(1); - - assertEquals(1, counter.get()); - } - } - - /* Method will execute only once and cache its result.*/ - @Test - public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { - - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future future = executor.submit(callable); - Observable source = Observable.fromFuture(future); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(1); - - assertEquals(1, counter.get()); - } - - executor.shutdown(); - } - - /* Method will execute every time it gets subscribed*/ - @Test - public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() { - - ExecutorService executor = Executors.newSingleThreadExecutor(); - Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); - - for (int i = 1; i < 5; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(i); - - assertEquals(i, counter.get()); - } - - executor.shutdown(); - } - - /*Method will execute only once and cache its result.*/ - @Test - public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { - List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); - ExecutorService exec = Executors.newSingleThreadExecutor(); - Callable> callable = () -> Observable.fromIterable(list); - Observable source = AsyncObservable.deferFuture(() -> exec.submit(callable)); - for (int i = 1; i < 4; i++) { - source.test() - .awaitDone(5, TimeUnit.SECONDS) - .assertResult(1, 2, 3); - } - - exec.shutdown(); - } - -} +package com.baeldung.rxjava; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import hu.akarnokd.rxjava2.async.AsyncObservable; +import io.reactivex.Observable; + +public class AsyncAndSyncToObservableIntegrationTest { + + AtomicInteger counter = new AtomicInteger(); + Callable callable = () -> counter.incrementAndGet(); + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenSyncMethod_whenConvertedWithFromCallable_thenReturnObservable() { + + Observable source = Observable.fromCallable(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenSyncMethod_whenConvertedWithStart_thenReturnObservable() { + + Observable source = AsyncObservable.start(callable); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + } + + /* Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithFromFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future future = executor.submit(callable); + Observable source = Observable.fromFuture(future); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1); + + assertEquals(1, counter.get()); + } + + executor.shutdown(); + } + + /* Method will execute every time it gets subscribed*/ + @Test + public void givenAsyncMethod_whenConvertedWithStartFuture_thenRetrunObservble() { + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Observable source = AsyncObservable.startFuture(() -> executor.submit(callable)); + + for (int i = 1; i < 5; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(i); + + assertEquals(i, counter.get()); + } + + executor.shutdown(); + } + + /*Method will execute only once and cache its result.*/ + @Test + public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { + List list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() }); + ExecutorService exec = Executors.newSingleThreadExecutor(); + Callable> callable = () -> Observable.fromIterable(list); + Observable source = AsyncObservable.deferFuture(() -> exec.submit(callable)); + for (int i = 1; i < 4; i++) { + source.test() + .awaitDone(5, TimeUnit.SECONDS) + .assertResult(1, 2, 3); + } + + exec.shutdown(); + } + +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java similarity index 100% rename from rxjava-2/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxFlatmapAndSwitchmapUnitTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java b/rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java similarity index 100% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java rename to rxjava-operators/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java diff --git a/rxjava/README.md b/rxjava/README.md deleted file mode 100644 index c9308ddcc6..0000000000 --- a/rxjava/README.md +++ /dev/null @@ -1,20 +0,0 @@ -## RxJava - -This module contains articles about RxJava. - -### Relevant articles: - -- [Dealing with Backpressure with RxJava](https://www.baeldung.com/rxjava-backpressure) -- [How to Test RxJava?](https://www.baeldung.com/rxjava-testing) -- [Implementing Custom Operators in RxJava](https://www.baeldung.com/rxjava-custom-operators) -- [Introduction to RxJava](https://www.baeldung.com/rx-java) -- [Observable Utility Operators in RxJava](https://www.baeldung.com/rxjava-observable-operators) -- [Introduction to rxjava-jdbc](https://www.baeldung.com/rxjava-jdbc) -- [Schedulers in RxJava](https://www.baeldung.com/rxjava-schedulers) -- [Mathematical and Aggregate Operators in RxJava](https://www.baeldung.com/rxjava-math) -- [Combining Observables in RxJava](https://www.baeldung.com/rxjava-combine-observables) -- [RxJava StringObservable](https://www.baeldung.com/rxjava-string) -- [Filtering Observables in RxJava](https://www.baeldung.com/rxjava-filtering) -- [RxJava One Observable, Multiple Subscribers](https://www.baeldung.com/rxjava-multiple-subscribers-observable) -- [Difference Between Flatmap and Switchmap in RxJava](https://www.baeldung.com/rxjava-flatmap-switchmap) -- More articles: [[next -->]](/rxjava-2) diff --git a/rxjava/src/main/resources/logback.xml b/rxjava/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/rxjava/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-5-data-reactive/README.md b/spring-5-data-reactive/README.md index 03bd323cb4..42fcba96f2 100644 --- a/spring-5-data-reactive/README.md +++ b/spring-5-data-reactive/README.md @@ -11,4 +11,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors) - [A Quick Look at R2DBC with Spring Data](https://www.baeldung.com/spring-data-r2dbc) - [Spring Data Reactive Repositories with Couchbase](https://www.baeldung.com/spring-data-reactive-couchbase) - diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java index 17eac7fee2..54f06d9c6c 100644 --- a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration; import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; @Configuration -//@EnableR2dbcRepositories(basePackages = "com.baeldung.r2dbc.repository") +@EnableR2dbcRepositories(basePackages = "com.baeldung.r2dbc.repository") public class R2DBCConfiguration extends AbstractR2dbcConfiguration { @Bean public H2ConnectionFactory connectionFactory() { diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java index 1926997e97..1e28cb3d07 100644 --- a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java @@ -4,10 +4,12 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; +import org.springframework.data.relational.core.mapping.Table; @Data @NoArgsConstructor @AllArgsConstructor +@Table public class Player { @Id Integer id; diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java index a31ef4458d..ffd2e98f8e 100644 --- a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java +++ b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java @@ -111,12 +111,12 @@ public class R2dbcApplicationIntegrationTest { private void insertPlayers() { List players = Arrays.asList( - new Player(1, "Kaka", 37), - new Player(2, "Messi", 32), - new Player(3, "Mbappé", 20), - new Player(4, "CR7", 34), - new Player(5, "Lewandowski", 30), - new Player(6, "Cavani", 32) + new Player(null, "Kaka", 37), + new Player(null, "Messi", 32), + new Player(null, "Mbappé", 20), + new Player(null, "CR7", 34), + new Player(null, "Lewandowski", 30), + new Player(null, "Cavani", 32) ); playerRepository.saveAll(players).subscribe(); diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index be21db481a..7417f39c21 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -46,14 +46,17 @@ org.jetbrains.kotlin kotlin-stdlib-jre8 + ${kotlin.version} org.jetbrains.kotlin kotlin-reflect + ${kotlin.version} com.fasterxml.jackson.module jackson-module-kotlin + ${jackson.version} @@ -170,7 +173,8 @@ 2.9.0 - 1.1.2 + 2.9.9 + 1.2.71 com.baeldung.Spring5Application 4.5.8 diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index 221c333d5b..bb308ae330 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -8,4 +8,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - [Logging Spring WebClient Calls](https://www.baeldung.com/spring-log-webclient-calls) - [Simultaneous Spring WebClient Calls](https://www.baeldung.com/spring-webclient-simultaneous-calls) - +- [Logging Spring WebClient Calls](https://www.baeldung.com/spring-log-webclient-calls) +- [Mocking a WebClient in Spring](https://www.baeldung.com/spring-mocking-webclient) diff --git a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java index 5d6c13bb0e..e2629053f1 100644 --- a/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java +++ b/spring-5-security-oauth/src/main/java/com/baeldung/oauth2/LoginController.java @@ -71,5 +71,4 @@ public class LoginController { return "loginSuccess"; } - } diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index 6887f01753..91272593d3 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -99,6 +99,6 @@ - 2.2.0.M3 + 2.2.0.RELEASE diff --git a/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java b/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java index 7dd3591cd6..abfe2e7807 100644 --- a/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java +++ b/spring-5-webflux/src/main/java/com/baeldung/spring/rsocket/client/ClientConfiguration.java @@ -25,6 +25,6 @@ public class ClientConfiguration { @Bean RSocketRequester rSocketRequester(RSocketStrategies rSocketStrategies) { - return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); + return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); } } diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java index ff00d5ec24..d22832b0fb 100644 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/client/MarketDataRestControllerIntegrationTest.java @@ -13,7 +13,6 @@ import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.messaging.rsocket.RSocketRequester; import org.springframework.messaging.rsocket.RSocketRequester.RequestSpec; -import org.springframework.messaging.rsocket.RSocketRequester.ResponseSpec; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.FluxExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -34,15 +33,12 @@ public class MarketDataRestControllerIntegrationTest { @Mock private RequestSpec requestSpec; - @Mock - private ResponseSpec responseSpec; - @Test public void whenInitiatesRequest_ThenGetsResponse() throws Exception { when(rSocketRequester.route("currentMarketData")).thenReturn(requestSpec); - when(requestSpec.data(any())).thenReturn(responseSpec); + when(requestSpec.data(any())).thenReturn(requestSpec); MarketData marketData = new MarketData("X", 1); - when(responseSpec.retrieveMono(MarketData.class)).thenReturn(Mono.just(marketData)); + when(requestSpec.retrieveMono(MarketData.class)).thenReturn(Mono.just(marketData)); testClient.get() .uri("/current/{stock}", "X") @@ -56,8 +52,8 @@ public class MarketDataRestControllerIntegrationTest { @Test public void whenInitiatesFireAndForget_ThenGetsNoResponse() throws Exception { when(rSocketRequester.route("collectMarketData")).thenReturn(requestSpec); - when(requestSpec.data(any())).thenReturn(responseSpec); - when(responseSpec.send()).thenReturn(Mono.empty()); + when(requestSpec.data(any())).thenReturn(requestSpec); + when(requestSpec.send()).thenReturn(Mono.empty()); testClient.get() .uri("/collect") @@ -70,10 +66,10 @@ public class MarketDataRestControllerIntegrationTest { @Test public void whenInitiatesRequest_ThenGetsStream() throws Exception { when(rSocketRequester.route("feedMarketData")).thenReturn(requestSpec); - when(requestSpec.data(any())).thenReturn(responseSpec); + when(requestSpec.data(any())).thenReturn(requestSpec); MarketData firstMarketData = new MarketData("X", 1); MarketData secondMarketData = new MarketData("X", 2); - when(responseSpec.retrieveFlux(MarketData.class)).thenReturn(Flux.just(firstMarketData, secondMarketData)); + when(requestSpec.retrieveFlux(MarketData.class)).thenReturn(Flux.just(firstMarketData, secondMarketData)); FluxExchangeResult result = testClient.get() .uri("/feed/{stock}", "X") @@ -89,4 +85,4 @@ public class MarketDataRestControllerIntegrationTest { .thenCancel() .verify(); } -} \ No newline at end of file +} diff --git a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java index dcf3b82730..40ddc732ac 100644 --- a/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java +++ b/spring-5-webflux/src/test/java/com/baeldung/spring/rsocket/server/MarketDataRSocketControllerLiveTest.java @@ -92,7 +92,7 @@ public class MarketDataRSocketControllerLiveTest { @Bean @Lazy RSocketRequester rSocketRequester(RSocketStrategies rSocketStrategies) { - return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); + return RSocketRequester.wrap(rSocket(), MimeTypeUtils.APPLICATION_JSON, MimeTypeUtils.APPLICATION_JSON, rSocketStrategies); } } -} \ No newline at end of file +} diff --git a/spring-5/README.md b/spring-5/README.md index 3f839a5bca..8a0cbe807e 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -15,4 +15,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring ResponseStatusException](https://www.baeldung.com/spring-response-status-exception) - [Spring Assert Statements](https://www.baeldung.com/spring-assert) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) -- [Difference between \ vs \](https://www.baeldung.com/spring-contextannotation-contextcomponentscan) +- [Difference between vs ](https://www.baeldung.com/spring-contextannotation-contextcomponentscan) diff --git a/spring-all/README.md b/spring-all/README.md new file mode 100644 index 0000000000..2b9f61c76d --- /dev/null +++ b/spring-all/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [The @Scheduled Annotation in Spring](https://www.baeldung.com/spring-scheduled-tasks) diff --git a/spring-batch/README.md b/spring-batch/README.md index 95abbaf931..9e09612490 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring Batch - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) - [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) +- [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index 48d3baeae3..e6d7cee6f2 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -78,36 +79,25 @@ org.springframework.boot spring-boot-starter-batch - ${spring.boot.version} org.hsqldb hsqldb - 2.5.0 runtime - + org.awaitility awaitility ${awaitility.version} test - - - org.springframework.boot - spring-boot-starter-test - ${spring.boot.version} - test - - 5.2.0.RELEASE 4.2.0.RELEASE - 2.1.9.RELEASE 3.15.1 4.1 2.3.1 diff --git a/spring-boot-admin/README.md b/spring-boot-admin/README.md index ac4d781d0e..1a7acef6c1 100644 --- a/spring-boot-admin/README.md +++ b/spring-boot-admin/README.md @@ -24,3 +24,4 @@ and the mail configuration from application.properties ### Relevant Articles: - [A Guide to Spring Boot Admin](https://www.baeldung.com/spring-boot-admin) +- [Changing the Logging Level at the Runtime for a Spring Boot Application](https://www.baeldung.com/spring-boot-changing-log-level-at-runtime) diff --git a/spring-boot-admin/pom.xml b/spring-boot-admin/pom.xml index 1c933723e7..c553790359 100644 --- a/spring-boot-admin/pom.xml +++ b/spring-boot-admin/pom.xml @@ -8,8 +8,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT @@ -17,20 +17,4 @@ spring-boot-admin-client - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - - - - 2.1.8.RELEASE - - - \ No newline at end of file + diff --git a/spring-boot-artifacts/README.md b/spring-boot-artifacts/README.md index 4025e43a65..876954e858 100644 --- a/spring-boot-artifacts/README.md +++ b/spring-boot-artifacts/README.md @@ -7,4 +7,5 @@ This module contains articles about configuring the Spring Boot build process. - [Create a Fat Jar App with Spring Boot](https://www.baeldung.com/deployable-fat-jar-spring-boot) - [Intro to Spring Boot Starters](https://www.baeldung.com/spring-boot-starters) - [Introduction to WebJars](https://www.baeldung.com/maven-webjars) - - [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper) \ No newline at end of file + - [A Quick Guide to Maven Wrapper](https://www.baeldung.com/maven-wrapper) + - [Running a Spring Boot App with Maven vs an Executable War/Jar](https://www.baeldung.com/spring-boot-run-maven-vs-executable-jar) diff --git a/spring-boot-autoconfiguration/README.md b/spring-boot-autoconfiguration/README.md index 180d857d52..b3a50ad7a5 100644 --- a/spring-boot-autoconfiguration/README.md +++ b/spring-boot-autoconfiguration/README.md @@ -10,4 +10,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Create a Custom Auto-Configuration with Spring Boot](https://www.baeldung.com/spring-boot-custom-auto-configuration) - [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner) - [A Guide to Spring Boot Configuration Metadata](https://www.baeldung.com/spring-boot-configuration-metadata) - diff --git a/spring-boot-configuration/README.md b/spring-boot-configuration/README.md index c449538a9d..af634aa5f4 100644 --- a/spring-boot-configuration/README.md +++ b/spring-boot-configuration/README.md @@ -3,3 +3,4 @@ This module contains articles about Spring Boot Configuration. ### Relevant Articles: +- [Unable to Find @SpringBootConfiguration with @DataJpaTest](https://www.baeldung.com/spring-boot-unable-to-find-springbootconfiguration-with-datajpatest) diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 91cc41d669..1528853b0c 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -7,24 +7,12 @@ greeter-spring-boot-sample-app - spring-boot-custom-starter + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT ../../spring-boot-custom-starter - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - com.baeldung @@ -51,8 +39,7 @@ - 1.5.15.RELEASE 0.0.1-SNAPSHOT - \ No newline at end of file + diff --git a/spring-boot-data/README.md b/spring-boot-data/README.md index 513c5fed18..eb3cd5bbaa 100644 --- a/spring-boot-data/README.md +++ b/spring-boot-data/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring Boot with Spring Data - [Formatting JSON Dates in Spring Boot](https://www.baeldung.com/spring-boot-formatting-json-dates) - [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) - [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) +- [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java index 8e4ee76a25..87656f66a6 100644 --- a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java @@ -1,12 +1,15 @@ package com.baeldung.disableautoconfig; +import org.javers.spring.boot.sql.JaversSqlAutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, + JaversSqlAutoConfiguration.class, SpringDataWebAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class SpringDataJPA { diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java index 865c137a8d..0845acee6e 100644 --- a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java @@ -3,9 +3,11 @@ package com.baeldung.disableautoconfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; -@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class}) +@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + SpringDataWebAutoConfiguration.class}) public class SpringDataMongoDB { public static void main(String[] args) { diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java index 9ec831c446..cd8cb0de09 100644 --- a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java @@ -4,8 +4,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration; +import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; -@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class}) +@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class, + SpringDataWebAutoConfiguration.class}) public class SpringDataRedis { public static void main(String[] args) { diff --git a/spring-boot-data/src/main/java/com/baeldung/javers/README.md b/spring-boot-data/src/main/java/com/baeldung/javers/README.md new file mode 100644 index 0000000000..4f8dd4abff --- /dev/null +++ b/spring-boot-data/src/main/java/com/baeldung/javers/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) diff --git a/spring-boot-deployment/README.md b/spring-boot-deployment/README.md index 6171decf2d..b6aa468098 100644 --- a/spring-boot-deployment/README.md +++ b/spring-boot-deployment/README.md @@ -6,4 +6,5 @@ This module contains articles about deployment of a Spring Boot Application - [Deploy a Spring Boot WAR into a Tomcat Server](https://www.baeldung.com/spring-boot-war-tomcat-deploy) - [Spring Boot Console Application](https://www.baeldung.com/spring-boot-console-app) - [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) - - [Comparing Embedded Servlet Containers in Spring Boot](https://www.baeldung.com/spring-boot-servlet-containers) \ No newline at end of file + - [Comparing Embedded Servlet Containers in Spring Boot](https://www.baeldung.com/spring-boot-servlet-containers) + - [Graceful Shutdown of a Spring Boot Application](https://www.baeldung.com/spring-boot-graceful-shutdown) diff --git a/spring-boot-di/README.MD b/spring-boot-di/README.MD index 6e2c495b88..cbd42c5609 100644 --- a/spring-boot-di/README.MD +++ b/spring-boot-di/README.MD @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) +- [Spring @ComponentScan – Filter Types](https://www.baeldung.com/spring-componentscan-filter-type) diff --git a/spring-boot-kotlin/pom.xml b/spring-boot-kotlin/pom.xml index 25508c52b9..ccb1585a75 100644 --- a/spring-boot-kotlin/pom.xml +++ b/spring-boot-kotlin/pom.xml @@ -30,19 +30,6 @@ - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - spring-snapshots @@ -81,7 +68,6 @@ org.springframework.boot spring-boot-starter-webflux - ${spring-boot.version} com.fasterxml.jackson.module @@ -160,7 +146,6 @@ 1.0.0.M7 1.0.0.BUILD-SNAPSHOT 1.2.1 - 2.2.0.M2 diff --git a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml index de2946fbb2..a64ebc246a 100644 --- a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml +++ b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -10,22 +10,10 @@ com.baeldung - spring-boot-parent - 1.0.0-SNAPSHOT + parent-boot-2 + 0.0.1-SNAPSHOT - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - org.springframework.boot @@ -35,7 +23,6 @@ 1.8 - 2.1.5.RELEASE diff --git a/spring-boot-properties/pom.xml b/spring-boot-properties/pom.xml index ccb9204d96..5e65aadc28 100644 --- a/spring-boot-properties/pom.xml +++ b/spring-boot-properties/pom.xml @@ -32,11 +32,6 @@ org.springframework.cloud spring-cloud-starter - - org.springframework.boot - spring-boot-starter-test - test - com.google.guava guava diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java index c15fcbd352..a506060d1c 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ChildConfig2.java @@ -16,7 +16,7 @@ public class ChildConfig2 { } @Bean - public static PropertyPlaceholderConfigurer configurer() { + public static PropertyPlaceholderConfigurer properties() { final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocations(new ClassPathResource("child.properties")); return ppc; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java index ddb59a5309..f5376e0c8e 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/parentchild/config/ParentConfig2.java @@ -16,7 +16,7 @@ public class ParentConfig2 { } @Bean - public static PropertyPlaceholderConfigurer configurer() { + public static PropertyPlaceholderConfigurer properties() { final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocations(new ClassPathResource("parent.properties")); return ppc; diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index ffac9335fd..3909a99c65 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -10,6 +10,7 @@ This module contains articles about Spring Boot RESTful APIs. - [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) - [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) - [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) +- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) ### E-book diff --git a/spring-boot/src/main/java/org/baeldung/model/User.java b/spring-boot/src/main/java/org/baeldung/model/User.java index 049b118b12..eb886338a0 100644 --- a/spring-boot/src/main/java/org/baeldung/model/User.java +++ b/spring-boot/src/main/java/org/baeldung/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.caching.model; +package org.baeldung.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index 0113c4c5d4..752664cd5d 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -1,6 +1,6 @@ package org.baeldung.repository; -import org.baeldung.caching.model.User; +import org.baeldung.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -15,7 +15,6 @@ import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.stream.Stream; @Repository("userRepository") public interface UserRepository extends JpaRepository { diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java index 54ce3b4bf3..ea7f118967 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -1,19 +1,17 @@ package org.baeldung.repository; import org.baeldung.boot.config.H2JpaConfig; -import org.baeldung.caching.model.User; +import org.baeldung.model.User; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; diff --git a/spring-cloud/spring-cloud-stream/README.md b/spring-cloud/spring-cloud-stream/README.md index fd1eeccfda..1fb0647ee3 100644 --- a/spring-cloud/spring-cloud-stream/README.md +++ b/spring-cloud/spring-cloud-stream/README.md @@ -4,3 +4,4 @@ This module contains articles about Spring Cloud Stream ## Relevant Articles - [Introduction to Spring Cloud Stream](http://www.baeldung.com/spring-cloud-stream) +- [Integrating Spring with AWS Kinesis](https://www.baeldung.com/spring-aws-kinesis) diff --git a/spring-cloud/spring-cloud-zuul-fallback/README.md b/spring-cloud/spring-cloud-zuul-fallback/README.md index 2f13c1923b..de5cfcef4b 100644 --- a/spring-cloud/spring-cloud-zuul-fallback/README.md +++ b/spring-cloud/spring-cloud-zuul-fallback/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Fallback for Zuul Route](TODO) +- [Fallback for Zuul Route](https://www.baeldung.com/spring-zuul-fallback-route) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index bcb1ce1fb4..ec6eb91306 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -15,4 +15,5 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- More articles: [[<-- prev]](/spring-core) \ No newline at end of file +- [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) +- More articles: [[<-- prev]](/spring-core) diff --git a/spring-core/README.md b/spring-core/README.md index 6d274e89f0..1f3dcb783b 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -4,9 +4,9 @@ This module contains articles about core Spring functionality ### Relevant Articles: - [Wiring in Spring: @Autowired, @Resource and @Inject](https://www.baeldung.com/spring-annotations-resource-inject-autowire) -- [Constructor Injection in Spring with Lombok](httsp://www.baeldung.com/spring-injection-lombok) +- [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) - [Introduction to Spring’s StreamUtils](https://www.baeldung.com/spring-stream-utils) -- [XML-Based Injection in Spring](httsp://www.baeldung.com/spring-xml-injection) +- [XML-Based Injection in Spring](https://www.baeldung.com/spring-xml-injection) - [A Quick Guide to the Spring @Lazy Annotation](https://www.baeldung.com/spring-lazy-annotation) - [BeanNameAware and BeanFactoryAware Interfaces in Spring](https://www.baeldung.com/spring-bean-name-factory-aware) - [Access a File from the Classpath in a Spring Application](https://www.baeldung.com/spring-classpath-file-access) diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java index ef86c2f36d..2d3dbc4c74 100644 --- a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java @@ -36,17 +36,17 @@ public class IntegrationTest { @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetJohn() throws Exception { // Get John - mockMvc.perform(get("/personQuery?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + mockMvc.perform(get("/users?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("John"))) .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) - .andExpect(jsonPath("$[0].address.country", is("Fake Country"))); + .andExpect(jsonPath("$[0].address.country", is("Spain"))); } @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetLisa() throws Exception { // Get Lisa - mockMvc.perform(get("/personQuery?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + mockMvc.perform(get("/users?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("Lisa"))) .andExpect(jsonPath("$[0].address.address", is("Real Street 1"))) - .andExpect(jsonPath("$[0].address.country", is("Real Country"))); + .andExpect(jsonPath("$[0].address.country", is("Germany"))); } } diff --git a/spring-ejb/README.md b/spring-ejb/README.md index 6c63c2709f..423d55ea22 100644 --- a/spring-ejb/README.md +++ b/spring-ejb/README.md @@ -6,7 +6,6 @@ This module contains articles about Spring with EJB - [Guide to EJB Set-up](https://www.baeldung.com/ejb-intro) - [Java EE Session Beans](https://www.baeldung.com/ejb-session-beans) -- [Introduction to EJB JNDI Lookup on WildFly Application Server](httpss://www.baeldung.com/wildfly-ejb-jndi) - [A Guide to Message Driven Beans in EJB](https://www.baeldung.com/ejb-message-driven-beans) - [Integration Guide for Spring and EJB](https://www.baeldung.com/spring-ejb) - [Singleton Session Bean in Java EE](https://www.baeldung.com/java-ee-singleton-session-bean) diff --git a/spring-ejb/pom.xml b/spring-ejb/pom.xml index 712bfc66ab..4422223c6f 100755 --- a/spring-ejb/pom.xml +++ b/spring-ejb/pom.xml @@ -4,6 +4,7 @@ 4.0.0 com.baeldung.spring.ejb spring-ejb + 1.0.0-SNAPSHOT spring-ejb pom Spring EJB Tutorial @@ -12,6 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-ejb/spring-ejb-client/README.md b/spring-ejb/spring-ejb-client/README.md new file mode 100644 index 0000000000..9addac7867 --- /dev/null +++ b/spring-ejb/spring-ejb-client/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to EJB JNDI Lookup on WildFly Application Server](https://www.baeldung.com/wildfly-ejb-jndi) diff --git a/spring-ejb/spring-ejb-client/pom.xml b/spring-ejb/spring-ejb-client/pom.xml index e0348d5ae3..2dd3120532 100644 --- a/spring-ejb/spring-ejb-client/pom.xml +++ b/spring-ejb/spring-ejb-client/pom.xml @@ -12,13 +12,13 @@ spring-ejb 1.0.0-SNAPSHOT - - + + org.springframework.boot spring-boot-dependencies - 2.0.4.RELEASE + ${spring-boot.version} pom import @@ -61,9 +61,13 @@ org.springframework.boot spring-boot-maven-plugin - 2.0.4.RELEASE + ${spring-boot.version} + + 2.0.4.RELEASE + + diff --git a/spring-ejb/spring-ejb-remote/README.md b/spring-ejb/spring-ejb-remote/README.md new file mode 100644 index 0000000000..9addac7867 --- /dev/null +++ b/spring-ejb/spring-ejb-remote/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to EJB JNDI Lookup on WildFly Application Server](https://www.baeldung.com/wildfly-ejb-jndi) diff --git a/spring-freemarker/README.md b/spring-freemarker/README.md index d9dfe16fbe..941777207f 100644 --- a/spring-freemarker/README.md +++ b/spring-freemarker/README.md @@ -5,4 +5,3 @@ This module contains articles about Spring with FreeMarker ### Relevant Articles: - [Introduction to Using FreeMarker in Spring MVC](https://www.baeldung.com/freemarker-in-spring-mvc-tutorial) - [FreeMarker Common Operations](https://www.baeldung.com/freemarker-operations) - diff --git a/spring-integration/README.md b/spring-integration/README.md index 2e719a8674..ad46082a04 100644 --- a/spring-integration/README.md +++ b/spring-integration/README.md @@ -7,6 +7,7 @@ This module contains articles about Spring Integration - [Security In Spring Integration](https://www.baeldung.com/spring-integration-security) - [Spring Integration Java DSL](https://www.baeldung.com/spring-integration-java-dsl) - [Using Subflows in Spring Integration](https://www.baeldung.com/spring-integration-subflows) +- [Transaction Support in Spring Integration](https://www.baeldung.com/spring-integration-transaction) ### Running the Sample Executing the `mvn exec:java` maven command (either from the command line or from an IDE) will start up the application. Follow the command prompt for further instructions. diff --git a/spring-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-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-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceUnitTest.java similarity index 95% rename from spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java rename to spring-mockito/src/test/java/com/baeldung/UserServiceUnitTest.java index 573a37a9a4..11c7b4d8a8 100644 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceUnitTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = MocksApplication.class) -public class UserServiceIntegrationUnitTest { +public class UserServiceUnitTest { @Autowired private UserService userService; diff --git a/spring-mvc-simple-2/README.md b/spring-mvc-simple-2/README.md index c03fa6363a..cff8891a1a 100644 --- a/spring-mvc-simple-2/README.md +++ b/spring-mvc-simple-2/README.md @@ -6,4 +6,8 @@ This module contains articles about Spring MVC - [How to Read HTTP Headers in Spring REST Controllers](https://www.baeldung.com/spring-rest-http-headers) - [A Custom Data Binder in Spring MVC](https://www.baeldung.com/spring-mvc-custom-data-binder) - [Validating Lists in a Spring Controller](https://www.baeldung.com/spring-validate-list-controller) +- [Spring Validation Message Interpolation](https://www.baeldung.com/spring-validation-message-interpolation) +- [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url) +- [Using Enums as Request Parameters in Spring](https://www.baeldung.com/spring-enum-request-param) +- [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) - More articles: [[<-- prev]](/spring-mvc-simple) diff --git a/spring-mvc-simple-2/src/main/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 bc530ba295..44a20e1527 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -15,5 +15,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java index f0e2473ec4..df750db1db 100644 --- a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java +++ b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java @@ -1,11 +1,7 @@ package com.baeldung.protobuf; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - +import com.baeldung.protobuf.BaeldungTraining.Course; +import com.googlecode.protobuf.format.JsonFormat; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; @@ -15,33 +11,38 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; -import com.baeldung.protobuf.BaeldungTraining.Course; -import com.googlecode.protobuf.format.JsonFormat; +import java.io.IOException; +import java.io.InputStream; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; @DirtiesContext @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationIntegrationTest { - private static final String COURSE1_URL = "http://localhost:8080/courses/1"; - @Autowired private RestTemplate restTemplate; + @LocalServerPort + private int port; + @Test public void whenUsingRestTemplate_thenSucceed() { - ResponseEntity course = restTemplate.getForEntity(COURSE1_URL, Course.class); + ResponseEntity course = restTemplate.getForEntity(getUrl(), Course.class); assertResponse(course.toString()); } @Test public void whenUsingHttpClient_thenSucceed() throws IOException { - InputStream responseStream = executeHttpRequest(COURSE1_URL); + InputStream responseStream = executeHttpRequest(getUrl()); String jsonOutput = convertProtobufMessageStreamToJsonString(responseStream); assertResponse(jsonOutput); } @@ -74,4 +75,8 @@ public class ApplicationIntegrationTest { assertThat(response, containsString("number")); assertThat(response, containsString("type")); } + + private String getUrl() { + return "http://localhost:" + port + "/courses/1"; + } } \ No newline at end of file diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 6d021eb400..8315d0ff6c 100644 --- a/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,16 +1,15 @@ package org.baeldung; +import com.baeldung.protobuf.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.protobuf.Application; - @DirtiesContext @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SpringContextIntegrationTest { @Test diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java index 4f655277b7..62a708b60a 100644 --- a/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java @@ -1,16 +1,15 @@ package org.baeldung; +import com.baeldung.protobuf.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.protobuf.Application; - @DirtiesContext @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SpringContextTest { @Test diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index a0ba8df27d..df7856725f 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -12,8 +12,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Integration Testing with the Maven Cargo plugin](https://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin) - [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](https://www.baeldung.com/spring-rest-api-metrics) -- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) - ### Build the Project ``` 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-rest/README.md b/spring-rest/README.md index ac12066e8f..af054b2dcf 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -10,16 +10,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Returning Custom Status Codes from Spring Controllers](https://www.baeldung.com/spring-mvc-controller-custom-http-status-code) - [Binary Data Formats in a Spring REST API](https://www.baeldung.com/spring-rest-api-with-binary-data-formats) - [Guide to UriComponentsBuilder in Spring](https://www.baeldung.com/spring-uricomponentsbuilder) -- [Introduction to FindBugs](https://www.baeldung.com/intro-to-findbugs) - [A Custom Media Type for a Spring REST API](https://www.baeldung.com/spring-rest-custom-media-type) - [HTTP PUT vs HTTP PATCH in a REST API](https://www.baeldung.com/http-put-patch-difference-spring) - [Spring – Log Incoming Requests](https://www.baeldung.com/spring-http-logging) -- [Introduction to CheckStyle](https://www.baeldung.com/checkstyle-java) - [How to Change the Default Port in Spring Boot](https://www.baeldung.com/spring-boot-change-port) - [Guide to DeferredResult in Spring](https://www.baeldung.com/spring-deferred-result) - [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) -- [Using the Spring RestTemplate Interceptor](https://www.baeldung.com/spring-rest-template-interceptor) -- [Get and Post Lists of Objects with RestTemplate](https://www.baeldung.com/spring-rest-template-list) - [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header) -- [Uploading MultipartFile with Spring RestTemplate](https://www.baeldung.com/spring-rest-template-multipart-upload) - [Download an Image or a File with Spring MVC](https://www.baeldung.com/spring-controller-return-image-file) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 93160a9936..fce04a8f2d 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -20,10 +20,7 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-thymeleaf - + org.springframework.boot spring-boot-starter-actuator @@ -141,11 +138,7 @@ commons-io ${commons-io.version} - - au.com.dius - pact-jvm-provider-junit_2.11 - ${pact.version} - + io.rest-assured rest-assured @@ -176,21 +169,7 @@ org.apache.maven.plugins maven-war-plugin - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - check - - - - + @@ -250,18 +229,7 @@ - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - + 1.3.2 @@ -275,7 +243,7 @@ 1.6.0 3.0.4 - 3.0.0 + false 2.2.0 diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index e98af0e787..054071a4df 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -13,3 +13,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) - [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) - [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) +- [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) +- [Copy of RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json-test) diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml index ae5cfed4c9..26a3143d6d 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -21,6 +21,10 @@ org.springframework.boot spring-boot-starter-actuator + + org.springframework.boot + spring-boot-starter-thymeleaf + org.springframework.boot spring-boot-devtools @@ -32,7 +36,13 @@ org.springframework.boot spring-boot-starter-test - test + + + + + au.com.dius + pact-jvm-provider-junit_2.11 + ${pact.version} @@ -111,11 +121,13 @@ + junit junit - test + 4.12 + org.hamcrest hamcrest-core @@ -295,6 +307,7 @@ 3.4.1 + 3.5.11 diff --git a/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-resttemplate/src/main/java/com/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java rename to spring-resttemplate/src/main/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/spring-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/SpringContextTest.java rename to spring-resttemplate/src/main/java/com/baeldung/SpringContextTest.java diff --git a/spring-rest/src/main/java/com/baeldung/changeport/CustomApplication.java b/spring-resttemplate/src/main/java/com/baeldung/changeport/CustomApplication.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/changeport/CustomApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/changeport/CustomApplication.java diff --git a/spring-rest/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java b/spring-resttemplate/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java rename to spring-resttemplate/src/main/java/com/baeldung/changeport/ServerPortCustomizer.java diff --git a/spring-rest/src/main/java/com/baeldung/produceimage/ImageApplication.java b/spring-resttemplate/src/main/java/com/baeldung/produceimage/ImageApplication.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/produceimage/ImageApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/produceimage/ImageApplication.java diff --git a/spring-rest/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java b/spring-resttemplate/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java rename to spring-resttemplate/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java diff --git a/spring-rest/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java b/spring-resttemplate/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java diff --git a/spring-rest/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java b/spring-resttemplate/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java rename to spring-resttemplate/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java diff --git a/spring-rest/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java b/spring-resttemplate/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java rename to spring-resttemplate/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java diff --git a/spring-rest/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java b/spring-resttemplate/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java rename to spring-resttemplate/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java diff --git a/spring-rest/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java b/spring-resttemplate/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java rename to spring-resttemplate/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java diff --git a/spring-rest/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java b/spring-resttemplate/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java rename to spring-resttemplate/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java b/spring-resttemplate/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/responseheaders/ResponseHeadersApplication.java diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java b/spring-resttemplate/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java rename to spring-resttemplate/src/main/java/com/baeldung/responseheaders/controllers/FilterResponseHeaderController.java diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java b/spring-resttemplate/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java rename to spring-resttemplate/src/main/java/com/baeldung/responseheaders/controllers/ResponseHeaderController.java diff --git a/spring-rest/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java b/spring-resttemplate/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java rename to spring-resttemplate/src/main/java/com/baeldung/responseheaders/filter/AddResponseHeaderFilter.java diff --git a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/EmployeeApplication.java diff --git a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java similarity index 68% rename from spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index 191719b084..49e375f9cc 100644 --- a/spring-rest/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-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/controller/EmployeeResource.java diff --git a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/dto/Employee.java diff --git a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/dto/EmployeeList.java diff --git a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java rename to spring-resttemplate/src/main/java/com/baeldung/resttemplate/lists/service/EmployeeService.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/MainApplication.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/config/MainApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/MainApplication.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java similarity index 97% rename from spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java index 8abc368bdb..cbaa21f4ca 100644 --- a/spring-rest/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java +++ b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/RestClientConfig.java @@ -1,29 +1,29 @@ -package com.baeldung.sampleapp.config; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.util.CollectionUtils; -import org.springframework.web.client.RestTemplate; - -import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor; - -@Configuration -public class RestClientConfig { - - @Bean - public RestTemplate restTemplate() { - RestTemplate restTemplate = new RestTemplate(); - - List interceptors = restTemplate.getInterceptors(); - if (CollectionUtils.isEmpty(interceptors)) { - interceptors = new ArrayList(); - } - interceptors.add(new RestTemplateHeaderModifierInterceptor()); - restTemplate.setInterceptors(interceptors); - return restTemplate; - } -} +package com.baeldung.sampleapp.config; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.util.CollectionUtils; +import org.springframework.web.client.RestTemplate; + +import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor; + +@Configuration +public class RestClientConfig { + + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(); + + List interceptors = restTemplate.getInterceptors(); + if (CollectionUtils.isEmpty(interceptors)) { + interceptors = new ArrayList(); + } + interceptors.add(new RestTemplateHeaderModifierInterceptor()); + restTemplate.setInterceptors(interceptors); + return restTemplate; + } +} diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/WebConfig.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/config/WebConfig.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/config/WebConfig.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java similarity index 97% rename from spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java index 519e5ebf0d..9ebe1553a5 100644 --- a/spring-rest/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java +++ b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/interceptors/RestTemplateHeaderModifierInterceptor.java @@ -1,18 +1,18 @@ -package com.baeldung.sampleapp.interceptors; - -import java.io.IOException; - -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; - -public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor { - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - ClientHttpResponse response = execution.execute(request, body); - response.getHeaders().add("Foo", "bar"); - return response; - } -} +package com.baeldung.sampleapp.interceptors; + +import java.io.IOException; + +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor { + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + ClientHttpResponse response = execution.execute(request, body); + response.getHeaders().add("Foo", "bar"); + return response; + } +} diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/repository/HeavyResourceRepository.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/BarMappingExamplesController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/CompanyController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/DeferredResultController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/HeavyResourceController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/ItemController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/PactController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Company.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Company.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Company.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResource.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressOnly.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/HeavyResourceAddressPartialUpdate.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Item.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Item.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Item.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/ItemManager.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/PactDto.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Views.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/dto/Views.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/Views.java diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java b/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java rename to spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/exception/ResourceNotFoundException.java diff --git a/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java b/spring-resttemplate/src/main/java/com/baeldung/transfer/LoginForm.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java rename to spring-resttemplate/src/main/java/com/baeldung/transfer/LoginForm.java diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/app/Application.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/web/log/app/Application.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/app/Application.java diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java similarity index 97% rename from spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java index b154f3665f..2ea0204dc3 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java +++ b/spring-resttemplate/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java @@ -1,44 +1,44 @@ -package com.baeldung.web.log.app; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; -import org.springframework.web.util.ContentCachingRequestWrapper; - -import com.baeldung.web.log.util.RequestLoggingUtil; - -@Component -public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { - - private final static Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class); - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - String postData; - HttpServletRequest requestCacheWrapperObject = null; - try { - // Uncomment to produce the stream closed issue - // postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream()); - - // To overcome request stream closed issue - requestCacheWrapperObject = new ContentCachingRequestWrapper(request); - requestCacheWrapperObject.getParameterMap(); - } catch (Exception exception) { - exception.printStackTrace(); - } finally { - postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject); - LOGGER.info("REQUEST DATA: " + postData); - } - return true; - } - - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { - LOGGER.info("RESPONSE: " + response.getStatus()); - } - -} +package com.baeldung.web.log.app; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import com.baeldung.web.log.util.RequestLoggingUtil; + +@Component +public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { + + private final static Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String postData; + HttpServletRequest requestCacheWrapperObject = null; + try { + // Uncomment to produce the stream closed issue + // postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream()); + + // To overcome request stream closed issue + requestCacheWrapperObject = new ContentCachingRequestWrapper(request); + requestCacheWrapperObject.getParameterMap(); + } catch (Exception exception) { + exception.printStackTrace(); + } finally { + postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject); + LOGGER.info("REQUEST DATA: " + postData); + } + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + LOGGER.info("RESPONSE: " + response.getStatus()); + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/config/CustomeRequestLoggingFilter.java diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java similarity index 97% rename from spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java index bc9ad1cf84..85728729d5 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java +++ b/spring-resttemplate/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java @@ -1,20 +1,20 @@ -package com.baeldung.web.log.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.filter.CommonsRequestLoggingFilter; - -@Configuration -public class RequestLoggingFilterConfig { - - @Bean - public CommonsRequestLoggingFilter logFilter() { - CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); - filter.setIncludeQueryString(true); - filter.setIncludePayload(true); - filter.setMaxPayloadLength(10000); - filter.setIncludeHeaders(false); - filter.setAfterMessagePrefix("REQUEST DATA : "); - return filter; - } -} +package com.baeldung.web.log.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.CommonsRequestLoggingFilter; + +@Configuration +public class RequestLoggingFilterConfig { + + @Bean + public CommonsRequestLoggingFilter logFilter() { + CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); + filter.setIncludeQueryString(true); + filter.setIncludePayload(true); + filter.setMaxPayloadLength(10000); + filter.setIncludeHeaders(false); + filter.setAfterMessagePrefix("REQUEST DATA : "); + return filter; + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java similarity index 97% rename from spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java index 8f1a000acc..fb0c1d1d48 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java +++ b/spring-resttemplate/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java @@ -1,19 +1,19 @@ -package com.baeldung.web.log.config; - -import com.baeldung.web.log.app.TaxiFareRequestInterceptor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class TaxiFareMVCConfig implements WebMvcConfigurer { - - @Autowired - private TaxiFareRequestInterceptor taxiFareRequestInterceptor; - - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/"); - } -} +package com.baeldung.web.log.config; + +import com.baeldung.web.log.app.TaxiFareRequestInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class TaxiFareMVCConfig implements WebMvcConfigurer { + + @Autowired + private TaxiFareRequestInterceptor taxiFareRequestInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/"); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/data/RateCard.java similarity index 95% rename from spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/data/RateCard.java index c7955b561b..e486d6b1f7 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java +++ b/spring-resttemplate/src/main/java/com/baeldung/web/log/data/RateCard.java @@ -1,31 +1,31 @@ -package com.baeldung.web.log.data; - -public class RateCard { - - private String nightSurcharge; - private String ratePerMile; - - public RateCard() { - nightSurcharge = "Extra $ 100"; - ratePerMile = "$ 10 Per Mile"; - } - - - public String getNightSurcharge() { - return nightSurcharge; - } - - public void setNightSurcharge(String nightSurcharge) { - this.nightSurcharge = nightSurcharge; - } - - public String getRatePerMile() { - return ratePerMile; - } - - public void setRatePerMile(String ratePerMile) { - this.ratePerMile = ratePerMile; - } - - -} +package com.baeldung.web.log.data; + +public class RateCard { + + private String nightSurcharge; + private String ratePerMile; + + public RateCard() { + nightSurcharge = "Extra $ 100"; + ratePerMile = "$ 10 Per Mile"; + } + + + public String getNightSurcharge() { + return nightSurcharge; + } + + public void setNightSurcharge(String nightSurcharge) { + this.nightSurcharge = nightSurcharge; + } + + public String getRatePerMile() { + return ratePerMile; + } + + public void setRatePerMile(String ratePerMile) { + this.ratePerMile = ratePerMile; + } + + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/data/TaxiRide.java similarity index 95% rename from spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/data/TaxiRide.java index 2e0f33f02b..6089c51996 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java +++ b/spring-resttemplate/src/main/java/com/baeldung/web/log/data/TaxiRide.java @@ -1,33 +1,33 @@ -package com.baeldung.web.log.data; - -public class TaxiRide { - - private Boolean isNightSurcharge; - private Long distanceInMile; - - public TaxiRide() { - } - - public TaxiRide(Boolean isNightSurcharge, Long distanceInMile) { - this.isNightSurcharge = isNightSurcharge; - this.distanceInMile = distanceInMile; - } - - - public Boolean getIsNightSurcharge() { - return isNightSurcharge; - } - - public void setIsNightSurcharge(Boolean isNightSurcharge) { - this.isNightSurcharge = isNightSurcharge; - } - - public Long getDistanceInMile() { - return distanceInMile; - } - - public void setDistanceInMile(Long distanceInMile) { - this.distanceInMile = distanceInMile; - } - -} +package com.baeldung.web.log.data; + +public class TaxiRide { + + private Boolean isNightSurcharge; + private Long distanceInMile; + + public TaxiRide() { + } + + public TaxiRide(Boolean isNightSurcharge, Long distanceInMile) { + this.isNightSurcharge = isNightSurcharge; + this.distanceInMile = distanceInMile; + } + + + public Boolean getIsNightSurcharge() { + return isNightSurcharge; + } + + public void setIsNightSurcharge(Boolean isNightSurcharge) { + this.isNightSurcharge = isNightSurcharge; + } + + public Long getDistanceInMile() { + return distanceInMile; + } + + public void setDistanceInMile(Long distanceInMile) { + this.distanceInMile = distanceInMile; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java similarity index 96% rename from spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java index 1176b31e4c..52a1698865 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java +++ b/spring-resttemplate/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java @@ -1,14 +1,14 @@ -package com.baeldung.web.log.service; - -import com.baeldung.web.log.data.TaxiRide; -import org.springframework.stereotype.Service; - -@Service -public class TaxiFareCalculatorService { - - public String calculateFare(TaxiRide taxiRide) { - return String.valueOf((Long) (taxiRide.getIsNightSurcharge() - ? taxiRide.getDistanceInMile() * 10 + 100 - : taxiRide.getDistanceInMile() * 10)); - } -} +package com.baeldung.web.log.service; + +import com.baeldung.web.log.data.TaxiRide; +import org.springframework.stereotype.Service; + +@Service +public class TaxiFareCalculatorService { + + public String calculateFare(TaxiRide taxiRide) { + return String.valueOf((Long) (taxiRide.getIsNightSurcharge() + ? taxiRide.getDistanceInMile() * 10 + 100 + : taxiRide.getDistanceInMile() * 10)); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java b/spring-resttemplate/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java similarity index 97% rename from spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java rename to spring-resttemplate/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java index c13d35b55c..70c4eaee90 100644 --- a/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java +++ b/spring-resttemplate/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java @@ -1,38 +1,38 @@ -package com.baeldung.web.log.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.io.IOUtils; -import org.springframework.web.util.ContentCachingRequestWrapper; -import org.springframework.web.util.WebUtils; - -public class RequestLoggingUtil { - - public static String getStringFromInputStream(InputStream is) { - StringWriter writer = new StringWriter(); - String encoding = "UTF-8"; - try { - IOUtils.copy(is, writer, encoding); - } catch (IOException e) { - e.printStackTrace(); - } - return writer.toString(); - } - - public static String readPayload(final HttpServletRequest request) throws IOException { - String payloadData = null; - ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); - if (null != contentCachingRequestWrapper) { - byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); - if (buf.length > 0) { - payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); - } - } - return payloadData; - } - -} +package com.baeldung.web.log.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.WebUtils; + +public class RequestLoggingUtil { + + public static String getStringFromInputStream(InputStream is) { + StringWriter writer = new StringWriter(); + String encoding = "UTF-8"; + try { + IOUtils.copy(is, writer, encoding); + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + public static String readPayload(final HttpServletRequest request) throws IOException { + String payloadData = null; + ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); + if (null != contentCachingRequestWrapper) { + byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); + if (buf.length > 0) { + payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); + } + } + return payloadData; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java b/spring-resttemplate/src/main/java/com/baeldung/web/upload/app/UploadApplication.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java rename to spring-resttemplate/src/main/java/com/baeldung/web/upload/app/UploadApplication.java diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-resttemplate/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java rename to spring-resttemplate/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java b/spring-resttemplate/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java similarity index 100% rename from spring-rest/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java rename to spring-resttemplate/src/main/java/com/baeldung/web/upload/controller/FileServerResource.java diff --git a/spring-rest/src/test/java/com/baeldung/pact/PactProviderLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/pact/PactProviderLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/pact/PactProviderLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/pact/PactProviderLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-resttemplate/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java rename to spring-resttemplate/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java diff --git a/spring-rest/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/controller/HeavyResourceControllerIntegrationTest.java diff --git a/spring-rest/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/controller/TaxiFareControllerIntegrationTest.java diff --git a/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java diff --git a/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java b/spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java rename to spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java diff --git a/spring-rest/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java b/spring-resttemplate/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java rename to spring-resttemplate/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java 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/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/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java b/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java index 75c700ee26..9f4b5d82a4 100644 --- a/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java +++ b/spring-vault/src/test/java/org/baeldung/springvault/VaultIntegrationTest.java @@ -1,36 +1,28 @@ package org.baeldung.springvault; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; -import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.core.annotation.Order; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.vault.authentication.TokenAuthentication; -import org.springframework.vault.client.VaultEndpoint; -import org.springframework.vault.core.VaultTemplate; -import org.springframework.vault.support.VaultResponse; +import java.net.URISyntaxException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * These tests are requiring the {@code vault} command to be installed and available in the executing + * platform. So, if you intend to run them in your environment, the please install the vault and then + * run the ignored tests. + */ @RunWith(SpringRunner.class) @SpringBootTest(classes = CredentialsService.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ContextConfiguration(classes = VaultTestConfiguration.class, loader = AnnotationConfigContextLoader.class) @@ -47,6 +39,7 @@ public class VaultIntegrationTest { * @throws URISyntaxException */ @Test + @Ignore public void givenCredentials_whenSecureCredentials_thenCredentialsSecured() throws URISyntaxException { try { // Given @@ -63,9 +56,11 @@ public class VaultIntegrationTest { /** * Test to access credentials + * * @throws URISyntaxException */ @Test + @Ignore public void whenAccessCredentials_thenCredentialsRetrieved() throws URISyntaxException { // Given 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 9dfa676c5c..4a31292683 100644 --- a/testing-modules/junit-5-advanced/README.md +++ b/testing-modules/junit-5-advanced/README.md @@ -3,4 +3,3 @@ - [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/spring-testing/README.md b/testing-modules/spring-testing/README.md index 1b06c13953..a4de9c5c57 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -6,3 +6,5 @@ - [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) +- [The Spring TestExecutionListener](https://www.baeldung.com/spring-testexecutionlistener) 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/testing-modules/testing-libraries/README.md b/testing-modules/testing-libraries/README.md index 7191989224..d76b7b1308 100644 --- a/testing-modules/testing-libraries/README.md +++ b/testing-modules/testing-libraries/README.md @@ -6,5 +6,7 @@ - [Cucumber and Scenario Outline](http://www.baeldung.com/cucumber-scenario-outline) - [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) - [Introduction to Lambda Behave](http://www.baeldung.com/lambda-behave) +- [Introduction to CheckStyle](https://www.baeldung.com/checkstyle-java) +- [Introduction to FindBugs](https://www.baeldung.com/intro-to-findbugs) diff --git a/spring-rest/checkstyle.xml b/testing-modules/testing-libraries/checkstyle.xml similarity index 100% rename from spring-rest/checkstyle.xml rename to testing-modules/testing-libraries/checkstyle.xml diff --git a/testing-modules/testing-libraries/pom.xml b/testing-modules/testing-libraries/pom.xml index 7891ebbf6d..0838e81d14 100644 --- a/testing-modules/testing-libraries/pom.xml +++ b/testing-modules/testing-libraries/pom.xml @@ -35,11 +35,60 @@ ${cucumber.version} test + + + org.springframework.boot + spring-boot-starter-web + 2.2.0.RELEASE + + + + testing-libraries + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + + check + + + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle-maven-plugin.version} + + checkstyle.xml + + + + + 0.4 1.2.5 + 3.0.0 diff --git a/testing-modules/testing-libraries/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java b/testing-modules/testing-libraries/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java new file mode 100644 index 0000000000..7b57d35088 --- /dev/null +++ b/testing-modules/testing-libraries/src/main/java/com/baeldung/sampleapp/web/controller/SimplePostController.java @@ -0,0 +1,74 @@ +package com.baeldung.sampleapp.web.controller; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.sampleapp.web.dto.Foo; + +// used to test HttpClientPostingTest +@RestController +public class SimplePostController { + + @RequestMapping(value = "/users", method = RequestMethod.POST) + public String postUser(@RequestParam final String username, @RequestParam final String password) { + return "Success" + username; + } + + @RequestMapping(value = "/users/detail", method = RequestMethod.POST) + public String postUserDetail(@RequestBody final Foo entity) { + return "Success" + entity.getId(); + } + + @RequestMapping(value = "/users/multipart", method = RequestMethod.POST) + public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) { + if (!file.isEmpty()) { + try { + final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss"); + final String fileName = dateFormat.format(new Date()); + final File fileServer = new File(fileName); + fileServer.createNewFile(); + final byte[] bytes = file.getBytes(); + final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer)); + stream.write(bytes); + stream.close(); + return "You successfully uploaded " + username; + } catch (final Exception e) { + return "You failed to upload " + e.getMessage(); + } + } else { + return "You failed to upload because the file was empty."; + } + } + + @RequestMapping(value = "/users/upload", method = RequestMethod.POST) + public String postMultipart(@RequestParam("file") final MultipartFile file) { + if (!file.isEmpty()) { + try { + final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss"); + final String fileName = dateFormat.format(new Date()); + final File fileServer = new File(fileName); + fileServer.createNewFile(); + final byte[] bytes = file.getBytes(); + final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer)); + stream.write(bytes); + stream.close(); + return "You successfully uploaded "; + } catch (final Exception e) { + return "You failed to upload " + e.getMessage(); + } + } else { + return "You failed to upload because the file was empty."; + } + } +} diff --git a/testing-modules/testing-libraries/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java b/testing-modules/testing-libraries/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java new file mode 100644 index 0000000000..de1d76ed92 --- /dev/null +++ b/testing-modules/testing-libraries/src/main/java/com/baeldung/sampleapp/web/dto/Foo.java @@ -0,0 +1,42 @@ +package com.baeldung.sampleapp.web.dto; + +public class Foo { + private long id; + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + public Foo(final long id, final String name) { + super(); + + this.id = id; + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + +} \ No newline at end of file diff --git a/wildfly/README.md b/wildfly/README.md new file mode 100644 index 0000000000..54d7d68691 --- /dev/null +++ b/wildfly/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Set Up a WildFly Server](https://www.baeldung.com/wildfly-server-setup) diff --git a/xml/README.md b/xml/README.md index b609a1e078..367a0334f6 100644 --- a/xml/README.md +++ b/xml/README.md @@ -6,9 +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)