diff --git a/algorithms-sorting-2/README.md b/algorithms-sorting-2/README.md index 897621bc41..71c9b8f86c 100644 --- a/algorithms-sorting-2/README.md +++ b/algorithms-sorting-2/README.md @@ -1,3 +1,7 @@ ### Relevant Articles: +- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) +- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) +- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting) - [Partitioning and Sorting Arrays with Many Repeated Entries](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries) +- More articles: [[<-- prev]](/algorithms-sorting) diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java similarity index 94% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java index b177bd60fc..148a9a21f9 100644 --- a/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java +++ b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/bynumber/NaturalOrderComparators.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.sort.bynumber; +package com.baeldung.algorithms.bynumber; import java.util.Comparator; diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java similarity index 100% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/inoutsort/InOutSort.java diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java b/algorithms-sorting-2/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java similarity index 100% rename from algorithms-sorting/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java rename to algorithms-sorting-2/src/main/java/com/baeldung/algorithms/stringsort/AnagramValidator.java diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java similarity index 95% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java index 2f05f62147..aaa5de87e1 100644 --- a/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java +++ b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java @@ -1,6 +1,5 @@ -package com.baeldung.algorithms.sort.bynumber; +package com.baeldung.algorithms.bynumber; -import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators; import org.junit.Test; import java.util.ArrayList; diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/AnagramValidatorUnitTest.java diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java b/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java similarity index 100% rename from algorithms-sorting/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java rename to algorithms-sorting-2/src/test/java/com/baeldung/algorithms/stringsort/SortStringUnitTest.java diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md index 15a5ec6e02..b4b90bf954 100644 --- a/algorithms-sorting/README.md +++ b/algorithms-sorting/README.md @@ -11,10 +11,7 @@ This module contains articles about sorting algorithms. - [Heap Sort in Java](https://www.baeldung.com/java-heap-sort) - [Shell Sort in Java](https://www.baeldung.com/java-shell-sort) - [Counting Sort in Java](https://www.baeldung.com/java-counting-sort) -- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) -- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting) - [Selection Sort in Java](https://www.baeldung.com/java-selection-sort) -- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers) - [Radix Sort in Java](https://www.baeldung.com/java-radix-sort) -- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) - [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort) +- More articles: [[next -->]](/algorithms-sorintg-2) diff --git a/cas/README.md b/cas/README.md index 16775a8a02..6ceeaea0c4 100644 --- a/cas/README.md +++ b/cas/README.md @@ -1,7 +1,18 @@ ## CAS -This module contains articles about the Central Authentication Service (CAS) +This module contains articles about the Central Authentication Service (CAS). + +The module consists of 2 submodules: +1. `cas-server` - it requires JDK11 and uses the Gradle War Overlay style to ease setup and deployment. To start the server, simply run: + +`./gradlew run + -Dorg.gradle.java.home=$JAVA11_HOME + -Pargs="-Dcas.standalone.configurationDirectory=/cas-server/src/main/resources/etc/cas/config"` + +The server starts at https://localhost:8443. `casuser`/`Mellon` are the username and password for logging in. + +2. `cas-secured-app` - A Maven based Springboot Application ### Relevant Articles: -- [CAS SSO With Spring Security](baeldung.com/spring-security-cas-sso) \ No newline at end of file +- [CAS SSO With Spring Security](https://www.baeldung.com/spring-security-cas-sso) \ No newline at end of file diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cas/pom.xml b/cas/pom.xml deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/core-java-modules/core-java-8-datetime-2/README.md b/core-java-modules/core-java-8-datetime-2/README.md new file mode 100644 index 0000000000..f16563aacc --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/README.md @@ -0,0 +1,5 @@ +### Relevant Articles: + +- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates) +- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values) +- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) \ No newline at end of file diff --git a/core-java-modules/core-java-datetime-java8-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml similarity index 91% rename from core-java-modules/core-java-datetime-java8-2/pom.xml rename to core-java-modules/core-java-8-datetime-2/pom.xml index a15113bddc..ce98b72781 100644 --- a/core-java-modules/core-java-datetime-java8-2/pom.xml +++ b/core-java-modules/core-java-8-datetime-2/pom.xml @@ -4,9 +4,9 @@ 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 - core-java-datetime-java8 + core-java-8-datetime ${project.parent.version} - core-java-datetime-java8 + core-java-8-datetime jar @@ -64,8 +64,8 @@ - 1.9 - 1.9 + 1.8 + 1.8 2.10 3.6.1 diff --git a/core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdate/LocalDateExample.java similarity index 100% rename from core-java-modules/core-java-datetime-java8-2/src/main/java/com/baeldung/localdate/LocalDateExample.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdate/LocalDateExample.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/LegacyRandomDateTimes.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDateTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDateTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDateTimes.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDates.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomDates.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomDates.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomTimes.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/random/RandomTimes.java rename to core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/random/RandomTimes.java diff --git a/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java similarity index 87% rename from core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java index dff15486a4..d65118ba3a 100644 --- a/core-java-modules/core-java-datetime-java8-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdate/LocalDateExampleUnitTest.java @@ -11,31 +11,31 @@ public class LocalDateExampleUnitTest { @Test public void givenValues_whenUsingOfMethod_thenLocalDate() { - assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8)); + assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8).toString()); } @Test public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() { - assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8)); + assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8).toString()); } @Test public void givenValues_whenUsingEpochDay_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromEpochDay(18269)); + assertEquals("2020-01-08", date.getDateFromEpochDay(18269).toString()); } @Test public void givenValues_whenUsingYearDay_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8)); + assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8).toString()); } @Test public void givenValues_whenUsingParse_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromString("2020-01-08")); + assertEquals("2020-01-08", date.getDateFromString("2020-01-08").toString()); } @Test public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() { - assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy")); + assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy").toString()); } } diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/LegacyRandomDateTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDateTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomDatesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomDatesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomTimesUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/random/RandomTimesUnitTest.java rename to core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/random/RandomTimesUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/README.md b/core-java-modules/core-java-8-datetime/README.md similarity index 92% rename from core-java-modules/core-java-datetime-java8/README.md rename to core-java-modules/core-java-8-datetime/README.md index dfbe9c997f..c35683a589 100644 --- a/core-java-modules/core-java-datetime-java8/README.md +++ b/core-java-modules/core-java-8-datetime/README.md @@ -13,4 +13,4 @@ This module contains articles about the Date and Time API introduced with Java 8 - [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) -- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates) +- [[Next -->]](/core-java-modules/core-java-datetime-java8-2) diff --git a/core-java-modules/core-java-datetime-java8/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml similarity index 91% rename from core-java-modules/core-java-datetime-java8/pom.xml rename to core-java-modules/core-java-8-datetime/pom.xml index a15113bddc..ce98b72781 100644 --- a/core-java-modules/core-java-datetime-java8/pom.xml +++ b/core-java-modules/core-java-8-datetime/pom.xml @@ -4,9 +4,9 @@ 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 - core-java-datetime-java8 + core-java-8-datetime ${project.parent.version} - core-java-datetime-java8 + core-java-8-datetime jar @@ -64,8 +64,8 @@ - 1.9 - 1.9 + 1.8 + 1.8 2.10 3.6.1 diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/DateTimeComparisonUtils.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/date/comparison/LegacyDateComparisonUtils.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDateTimeFormatter.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDuration.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseDuration.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseDuration.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDate.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDate.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDate.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseLocalTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseLocalTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseOffsetDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UsePeriod.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UsePeriod.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UsePeriod.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseToInstant.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseToInstant.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseToInstant.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseZonedDateTime.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/datetime/UseZonedDateTime.java diff --git a/core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java rename to core-java-modules/core-java-8-datetime/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/DateTimeComparisonUtilsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/Java8DateTimeApiGeneralComparisonsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/date/comparison/LegacyDateComparisonUtilsUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/ConversionExample.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/ConversionExample.java rename to core-java-modules/core-java-8-datetime/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-8-datetime/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaDurationUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaPeriodUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseDateTimeFormatterUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseOffsetDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseTimeZoneUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseToInstantUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java diff --git a/core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java b/core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java similarity index 100% rename from core-java-modules/core-java-datetime-java8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java rename to core-java-modules/core-java-8-datetime/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java new file mode 100644 index 0000000000..391a059f05 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/computeifabsent/ComputeIfAbsentUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.map.computeifabsent; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class ComputeIfAbsentUnitTest { + + @Test + public void whenKeyIsPresent_thenFetchTheValue() { + Map stringLength = new HashMap<>(); + stringLength.put("John", 5); + assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 5); + } + + @Test + public void whenKeyIsNotPresent_thenComputeTheValueUsingMappingFunctionAndStore() { + Map stringLength = new HashMap<>(); + assertEquals((long)stringLength.computeIfAbsent("John", s -> s.length()), 4); + assertEquals((long)stringLength.get("John"), 4); + } + + @Test + public void whenMappingFunctionReturnsNull_thenDoNotRecordMapping() { + Map stringLength = new HashMap<>(); + assertEquals(stringLength.computeIfAbsent("John", s -> null), null); + assertNull(stringLength.get("John")); + } + + @Test(expected = RuntimeException.class) + public void whenMappingFunctionThrowsException_thenExceptionIsRethrown() { + Map stringLength = new HashMap<>(); + stringLength.computeIfAbsent("John", s -> {throw new RuntimeException();}); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java new file mode 100644 index 0000000000..1a46e1ba52 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java @@ -0,0 +1,34 @@ +package com.baeldung.atomicstampedreference; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicStampedReference; + +public class StampedAccount { + + private AtomicInteger stamp = new AtomicInteger(0); + private AtomicStampedReference account = new AtomicStampedReference<>(0, 0); + + public int getBalance() { + return this.account.get(new int[1]); + } + + public int getStamp() { + int[] stamps = new int[1]; + this.account.get(stamps); + return stamps[0]; + } + + public boolean deposit(int funds) { + int[] stamps = new int[1]; + int current = this.account.get(stamps); + int newStamp = this.stamp.incrementAndGet(); + return this.account.compareAndSet(current, current + funds, stamps[0], newStamp); + } + + public boolean withdrawal(int funds) { + int[] stamps = new int[1]; + int current = this.account.get(stamps); + int newStamp = this.stamp.incrementAndGet(); + return this.account.compareAndSet(current, current - funds, stamps[0], newStamp); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java new file mode 100644 index 0000000000..ce83355073 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.atomicstampedreference; + +import org.junit.Assert; +import org.junit.Test; + +public class ThreadStampedAccountUnitTest { + + @Test + public void givenMultiThread_whenStampedAccount_thenSetBalance() throws InterruptedException { + StampedAccount account = new StampedAccount(); + Thread t = new Thread(() -> { + while (!account.withdrawal(100)) + Thread.yield(); + }); + t.start(); + Assert.assertTrue(account.deposit(100)); + t.join(1_000); + Assert.assertFalse(t.isAlive()); + Assert.assertSame(0, account.getBalance()); + } +} diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java index 5fcb28cd2a..ebd027ea68 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/application/Application.java @@ -9,7 +9,7 @@ import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCount import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable; import com.baeldung.concurrent.threadsafety.services.AtomicCounter; import com.baeldung.concurrent.threadsafety.services.Counter; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import com.baeldung.concurrent.threadsafety.services.MessageService; import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter; import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter; @@ -48,9 +48,9 @@ public class Application { System.out.println(future3.get()); System.out.println(future4.get()); - ExtrinsicLockCounter extrinsicLockCounter = new ExtrinsicLockCounter(); - Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); - Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(extrinsicLockCounter)); + ObjectLockCounter objectLockCounter = new ObjectLockCounter(); + Future future5 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(objectLockCounter)); + Future future6 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(objectLockCounter)); System.out.println(future5.get()); System.out.println(future6.get()); diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java index 370e5d1f00..dcc929d3c4 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/callables/ExtrinsicLockCounterCallable.java @@ -1,13 +1,13 @@ package com.baeldung.concurrent.threadsafety.callables; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import java.util.concurrent.Callable; public class ExtrinsicLockCounterCallable implements Callable { - private final ExtrinsicLockCounter counter; + private final ObjectLockCounter counter; - public ExtrinsicLockCounterCallable(ExtrinsicLockCounter counter) { + public ExtrinsicLockCounterCallable(ObjectLockCounter counter) { this.counter = counter; } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java similarity index 84% rename from core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java rename to core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java index 0a6ff3f60e..f31cf899ba 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ExtrinsicLockCounter.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/threadsafety/services/ObjectLockCounter.java @@ -1,11 +1,11 @@ package com.baeldung.concurrent.threadsafety.services; -public class ExtrinsicLockCounter { +public class ObjectLockCounter { private int counter; private final Object lock = new Object(); - public ExtrinsicLockCounter() { + public ObjectLockCounter() { this.counter = 0; } diff --git a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java similarity index 82% rename from core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java rename to core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java index 0fc3dd3a54..b0ac80a3aa 100644 --- a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ExtrinsicLockCounterUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/threadsafety/ObjectLockCounterUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.concurrent.threadsafety; import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable; -import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter; +import com.baeldung.concurrent.threadsafety.services.ObjectLockCounter; import org.junit.Test; import java.util.concurrent.ExecutorService; @@ -10,12 +10,12 @@ import java.util.concurrent.Future; import static org.assertj.core.api.Assertions.assertThat; -public class ExtrinsicLockCounterUnitTest { +public class ObjectLockCounterUnitTest { @Test public void whenCalledIncrementCounter_thenCorrect() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(2); - ExtrinsicLockCounter counter = new ExtrinsicLockCounter(); + ObjectLockCounter counter = new ObjectLockCounter(); Future future1 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); Future future2 = (Future) executorService.submit(new ExtrinsicLockCounterCallable(counter)); diff --git a/core-java-modules/core-java-datetime-java8-2/README.md b/core-java-modules/core-java-datetime-java8-2/README.md deleted file mode 100644 index e53d0236c2..0000000000 --- a/core-java-modules/core-java-datetime-java8-2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values) diff --git a/core-java-modules/core-java-io-conversions-2/README.md b/core-java-modules/core-java-io-conversions-2/README.md new file mode 100644 index 0000000000..4a28bf37c5 --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/README.md @@ -0,0 +1,9 @@ +## Core Java IO Conversions (Part 2) + +This module contains articles about core Java input/output(IO) conversions. + +### Relevant Articles: +- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string) +- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) +- [Java – Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file) +- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions) diff --git a/core-java-modules/core-java-io-conversions-2/pom.xml b/core-java-modules/core-java-io-conversions-2/pom.xml new file mode 100644 index 0000000000..e95d1f4b67 --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + core-java-io-conversions-2 + 0.1.0-SNAPSHOT + core-java-io-conversions-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + core-java-io-conversions + + + src/main/resources + true + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java rename to core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java diff --git a/core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java rename to core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java diff --git a/core-java-modules/core-java-io-conversions/src/test/resources/targetFile.tmp b/core-java-modules/core-java-io-conversions-2/src/test/resources/sample.txt similarity index 100% rename from core-java-modules/core-java-io-conversions/src/test/resources/targetFile.tmp rename to core-java-modules/core-java-io-conversions-2/src/test/resources/sample.txt diff --git a/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp b/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp new file mode 100644 index 0000000000..5e1c309dae --- /dev/null +++ b/core-java-modules/core-java-io-conversions-2/src/test/resources/targetFile.tmp @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/core-java-modules/core-java-io-conversions/README.md b/core-java-modules/core-java-io-conversions/README.md index cdb7df04d0..1f12c87241 100644 --- a/core-java-modules/core-java-io-conversions/README.md +++ b/core-java-modules/core-java-io-conversions/README.md @@ -3,10 +3,8 @@ This module contains articles about core Java input/output(IO) conversions. ### Relevant Articles: -- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string) - [Java – Convert File to InputStream](https://www.baeldung.com/convert-file-to-input-stream) - [Java – Byte Array to Writer](https://www.baeldung.com/java-convert-byte-array-to-writer) -- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) - [Java – String to Reader](https://www.baeldung.com/java-convert-string-to-reader) - [Java – Byte Array to Reader](https://www.baeldung.com/java-convert-byte-array-to-reader) - [Java – File to Reader](https://www.baeldung.com/java-convert-file-to-reader) @@ -15,3 +13,4 @@ This module contains articles about core Java input/output(IO) conversions. - [Java – Write a Reader to File](https://www.baeldung.com/java-write-reader-to-file) - [Java – Reader to Byte Array](https://www.baeldung.com/java-convert-reader-to-byte-array) - [Java – Reader to InputStream](https://www.baeldung.com/java-convert-reader-to-inputstream) +- More articles: [[next -->]](/core-java-modules/core-java-io-conversions-2) diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java new file mode 100644 index 0000000000..360fb6ecaa --- /dev/null +++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/connectexception/ConnectionChecker.java @@ -0,0 +1,24 @@ +package com.baeldung.connectexception; + +import java.net.ConnectException; +import java.net.Socket; + +public class ConnectionChecker { + public static void main(String[] args) { + String host = "localhost"; + int port = 5000; + + try { + Socket clientSocket = new Socket(host, port); + + // successfully connected to host, do something with opened socket + + clientSocket.close(); + } catch (ConnectException e) { + // host and port combination not valid + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java index e5c4319bf7..de16e9b635 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -86,6 +86,15 @@ public class OptionalUnitTest { Optional opt = Optional.ofNullable(null); String name = opt.get(); } + + @Test + public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() { + Optional opt = Optional.of("Baeldung"); + assertTrue(opt.isPresent()); + + opt = Optional.ofNullable(null); + assertFalse(opt.isPresent()); + } // Conditional Return With filter() @Test diff --git a/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java new file mode 100644 index 0000000000..10e5716e31 --- /dev/null +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/closure/StreamClosureSnippets.java @@ -0,0 +1,30 @@ +package com.baeldung.streams.closure; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.stream.Stream; + +/** + * Contains a couple of simple stream API usages. + */ +public class StreamClosureSnippets { + + public static void main(String[] args) throws IOException { + // Collection based streams shouldn't be closed + Arrays.asList("Red", "Blue", "Green") + .stream() + .filter(c -> c.length() > 4) + .map(String::toUpperCase) + .forEach(System.out::print); + + String[] colors = {"Red", "Blue", "Green"}; + Arrays.stream(colors).map(String::toUpperCase).forEach(System.out::println); + + // IO-Based Streams Should be Closed via Try with Resources + try (Stream lines = Files.lines(Paths.get("/path/tp/file"))) { + // lines will be closed after exiting the try block + } + } +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 3fc978a68c..00ef24be92 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -69,6 +69,7 @@ core-java-io-2 core-java-io-apis core-java-io-conversions + core-java-io-conversions-2 core-java-jar core-java-jndi diff --git a/ddd-modules/pom.xml b/ddd-modules/pom.xml index 38e48ff27d..c6dd6e1f25 100644 --- a/ddd-modules/pom.xml +++ b/ddd-modules/pom.xml @@ -5,7 +5,7 @@ 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.dddmodules - dddmodules + ddd-modules 1.0 ddd-modules pom diff --git a/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java index a264dd52f2..924ec1162f 100644 --- a/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java +++ b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/date/JacksonDateUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.jackson.date; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -8,6 +9,8 @@ import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; import java.util.Date; import java.util.TimeZone; @@ -30,7 +33,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class JacksonDateUnitTest { @Test - public void whenSerializingDateWithJackson_thenSerializedToNumber() throws JsonProcessingException, ParseException { + public void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProcessingException, ParseException { final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); df.setTimeZone(TimeZone.getTimeZone("UTC")); @@ -61,6 +64,21 @@ public class JacksonDateUnitTest { final String result = mapper.writeValueAsString(event); assertThat(result, containsString("1970-01-01T02:30:00.000+00:00")); } + + @Test + public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect() + throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC")); + String converted = objectMapper.writeValueAsString(now); + + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(restored)); + } @Test public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException { diff --git a/jgit/pom.xml b/jgit/pom.xml index eef3c9b8e8..d960843868 100644 --- a/jgit/pom.xml +++ b/jgit/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - JGit + jgit 1.0-SNAPSHOT - JGit + jgit jar http://maven.apache.org diff --git a/jws/pom.xml b/jws/pom.xml index f867df8051..be42798fd1 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -14,21 +14,6 @@ 1.0.0-SNAPSHOT - - - OpenNMS Repository - https://repo.opennms.org/maven2/ - - - - - - javax.samples.jnlp - jnlp-servlet - ${jnlp-servlet.version} - - - ${project.artifactId} @@ -79,7 +64,6 @@ 3.0.2 - 1.6.0 diff --git a/libraries-2/README.md b/libraries-2/README.md index eb45a3e426..edf513c6ee 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -14,11 +14,9 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) - [Templating with Handlebars](https://www.baeldung.com/handlebars) - [A Guide to Crawler4j](https://www.baeldung.com/crawler4j) -- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) - [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) -- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) - More articles [[<-- prev]](/libraries) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 474ff563c2..3aa36c3f90 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -75,28 +75,7 @@ - - - com.squareup.okhttp3 - okhttp - ${okhttp.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.google.code.gson - gson - ${gson.version} - - - com.squareup.okhttp3 - mockwebserver - ${mockwebserver.version} - test - + edu.uci.ics crawler4j @@ -151,9 +130,6 @@ 2.1.4.RELEASE 0.28.3 1.1.0 - 3.14.2 - 2.8.5 - 3.14.2 4.1.2 6.6.0 5.1.9.RELEASE diff --git a/libraries-http-2/README.md b/libraries-http-2/README.md new file mode 100644 index 0000000000..5ba45eb4a9 --- /dev/null +++ b/libraries-http-2/README.md @@ -0,0 +1,10 @@ +## HTTP + +This module contains articles about HTTP libraries. + +### Relevant Articles: + +- [Jetty ReactiveStreams HTTP Client](https://www.baeldung.com/jetty-reactivestreams-http-client) +- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) +- More articles [[<-- prev]](/libraries-http) + diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml new file mode 100644 index 0000000000..c0a4f6455d --- /dev/null +++ b/libraries-http-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + libraries-http-2 + libraries-http-2 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + com.squareup.okhttp3 + okhttp + ${okhttp.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.google.code.gson + gson + ${gson.version} + + + com.squareup.okhttp3 + mockwebserver + ${mockwebserver.version} + test + + + + + 3.14.2 + 2.8.5 + 3.14.2 + 2.9.8 + + + diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java similarity index 100% rename from libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java rename to libraries-http-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java b/libraries-http-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java similarity index 100% rename from libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java rename to libraries-http-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java diff --git a/libraries-http/README.md b/libraries-http/README.md index 1f065a9d4a..61b2904cee 100644 --- a/libraries-http/README.md +++ b/libraries-http/README.md @@ -14,3 +14,4 @@ This module contains articles about HTTP libraries. - [Creating REST Microservices with Javalin](https://www.baeldung.com/javalin-rest-microservices) - [A Quick Guide to Timeouts in OkHttp](https://www.baeldung.com/okhttp-timeouts) - [A Quick Guide to Post Requests with OkHttp](https://www.baeldung.com/okhttp-post) +- More articles [[next -->]](/libraries-http-2) diff --git a/libraries-server/README.md b/libraries-server/README.md index d9e6b8b206..7e41f33a0c 100644 --- a/libraries-server/README.md +++ b/libraries-server/README.md @@ -13,3 +13,4 @@ This module contains articles about server libraries. - [MQTT Client in Java](https://www.baeldung.com/java-mqtt-client) - [Guide to XMPP Smack Client](https://www.baeldung.com/xmpp-smack-chat-client) - [A Guide to NanoHTTPD](https://www.baeldung.com/nanohttpd) +- [HTTP/2 in Jetty](https://www.baeldung.com/jetty-http-2) diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index a849708cd8..eb9cb61e56 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -5,6 +5,7 @@ libraries-server 0.0.1-SNAPSHOT libraries-server + war com.baeldung @@ -105,12 +106,51 @@ + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + 8888 + quit + + -Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.version}/alpn-boot-${alpn.version}.jar + + ${basedir}/src/main/config/jetty.xml + + / + + + + + org.eclipse.jetty.http2 + http2-server + ${jetty.version} + + + org.eclipse.jetty + jetty-alpn-openjdk8-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlets + ${jetty.version} + + + + + 3.6.2 4.5.3 - 9.4.8.v20171121 + 9.4.27.v20200227 4.1.20.Final + 8.1.11.v20170118 8.5.24 4.3.1 1.2.0 diff --git a/libraries-server/src/main/config/jetty.xml b/libraries-server/src/main/config/jetty.xml new file mode 100644 index 0000000000..fd4a50382b --- /dev/null +++ b/libraries-server/src/main/config/jetty.xml @@ -0,0 +1,79 @@ + + + + + + + src/main/resources/keystore.jks + storepwd + src/main/resources/truststore.jks + storepwd + TLSv1.2 + + + + + + + + + + + + + + + + + http/1.1 + + + + + + + + + + + + 8443 + + + + + + + + + + + + + + + + + + alpn + + + + + h2,h2-17 + + + + + + + + + + + + 8444 + + + + \ No newline at end of file diff --git a/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java b/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java new file mode 100644 index 0000000000..56b75c45d3 --- /dev/null +++ b/libraries-server/src/main/java/com/baeldung/jetty/http2/Http2JettyServlet.java @@ -0,0 +1,29 @@ +package com.baeldung.jetty.http2; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class Http2JettyServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.addHeader("Cache-control", "no-store, no-cache, must-revalidate"); + response.addDateHeader("Last-Modified", 0); + response.addDateHeader("Expires", 0); + + String requestPath = request.getRequestURI(); + InputStream input = getServletContext().getResourceAsStream(requestPath); + OutputStream output = response.getOutputStream(); + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + output.write(buffer, 0, read); + } + } + +} diff --git a/libraries-server/src/main/resources/keystore.jks b/libraries-server/src/main/resources/keystore.jks new file mode 100644 index 0000000000..428ba54776 Binary files /dev/null and b/libraries-server/src/main/resources/keystore.jks differ diff --git a/libraries-server/src/main/resources/truststore.jks b/libraries-server/src/main/resources/truststore.jks new file mode 100644 index 0000000000..839cb8c351 Binary files /dev/null and b/libraries-server/src/main/resources/truststore.jks differ diff --git a/libraries-server/src/main/webapp/WEB-INF/web.xml b/libraries-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..75d7e11c64 --- /dev/null +++ b/libraries-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,33 @@ + + + + + http2Jetty + com.baeldung.jetty.http2.Http2JettyServlet + + + http2Jetty + /images/* + + + + push + org.eclipse.jetty.servlets.PushCacheFilter + + ports + 8444 + + + maxAssociations + 32 + + + + push + /* + + + \ No newline at end of file diff --git a/libraries-server/src/main/webapp/http2.html b/libraries-server/src/main/webapp/http2.html new file mode 100644 index 0000000000..4563945a5e --- /dev/null +++ b/libraries-server/src/main/webapp/http2.html @@ -0,0 +1,14 @@ + + + + Baeldung HTTP/2 Client in Jetty + + +

HTTP/2 Demo

+
+ latest articles + rest with spring + weekly reviews +
+ + \ No newline at end of file diff --git a/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg b/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg new file mode 100644 index 0000000000..59e78e4560 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-latest_articles.jpg differ diff --git a/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg b/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg new file mode 100644 index 0000000000..43d9221e85 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-rest_with_spring.jpg differ diff --git a/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg b/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg new file mode 100644 index 0000000000..0d6d111911 Binary files /dev/null and b/libraries-server/src/main/webapp/images/homepage-weekly_reviews.jpg differ diff --git a/libraries-server/src/main/webapp/index.html b/libraries-server/src/main/webapp/index.html new file mode 100644 index 0000000000..2497893d82 --- /dev/null +++ b/libraries-server/src/main/webapp/index.html @@ -0,0 +1,12 @@ + + + + Baeldung: HTTP2 Client in Jetty + + +

HTTP/1.1

+
+

HTTP/2 Push

+
+ + \ No newline at end of file diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index 55197ad560..70ff8d6a87 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -6,7 +6,7 @@ com.baeldung.examples.r2dbc r2dbc-example 0.0.1-SNAPSHOT - r2dbc-example + r2dbc Sample R2DBC Project diff --git a/persistence-modules/sirix/pom.xml b/persistence-modules/sirix/pom.xml index d8e065ec2f..0f114966f7 100644 --- a/persistence-modules/sirix/pom.xml +++ b/persistence-modules/sirix/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.sirix - core-api-tutorial + sirix 1.0-SNAPSHOT core-api-tutorial jar diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 048dd45c7f..9f456fa8af 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -43,7 +43,12 @@ org.springframework.boot - spring-boot-starter-jdbc + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa @@ -82,6 +87,23 @@ spring-boot-starter-test test + + + com.mchange + c3p0 + ${c3p0.version} + + + + org.apache.commons + commons-dbcp2 + + + + org.apache.tomcat + tomcat-jdbc + + @@ -90,12 +112,30 @@ org.springframework.boot spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java + com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java + + + com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java + com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java + + +
3.9.1 2.1.8.RELEASE + 0.9.5.2 diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java new file mode 100644 index 0000000000..fa7f884112 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.oracle.pooling; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import lombok.extern.slf4j.Slf4j; + +@SpringBootApplication +@Slf4j +public class SpringOraclePoolingApplication implements CommandLineRunner{ + + @Autowired + private DataSource dataSource; + + public static void main(String[] args) { + SpringApplication.run(SpringOraclePoolingApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + log.info("Connection Polling datasource : "+ dataSource); + + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java new file mode 100644 index 0000000000..f357924807 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/C3P0Configuration.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import com.mchange.v2.c3p0.ComboPooledDataSource; + +@Configuration +@Profile("c3p0") +public class C3P0Configuration { + + @Bean + public DataSource dataSource() throws SQLException { + ComboPooledDataSource dataSource = new ComboPooledDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setJdbcUrl("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + dataSource.setMinPoolSize(5); + dataSource.setMaxPoolSize(10); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java new file mode 100644 index 0000000000..9cf7e27c99 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import oracle.jdbc.pool.OracleDataSource; + +@Configuration +@Profile("oracle") +public class OracleConfiguration { + + @Bean + public DataSource dataSource() throws SQLException { + OracleDataSource dataSource = new OracleDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + dataSource.setFastConnectionFailoverEnabled(true); + dataSource.setImplicitCachingEnabled(true); + // Only with clients prior to v11.2 + // dataSource.setConnectionCachingEnabled(true); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java new file mode 100644 index 0000000000..b4c1544149 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.oracle.pooling.configuration; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import oracle.ucp.jdbc.PoolDataSource; +import oracle.ucp.jdbc.PoolDataSourceFactory; + +@Configuration +@Profile("oracle-ucp") +public class OracleUCPConfiguration { + + @Bean + public DataSource dataSource() throws SQLException { + PoolDataSource dataSource = PoolDataSourceFactory.getPoolDataSource(); + dataSource.setUser("books"); + dataSource.setPassword("books"); + dataSource.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource"); + dataSource.setURL("jdbc:oracle:thin:@//localhost:11521/ORCLPDB1"); + + dataSource.setFastConnectionFailoverEnabled(true); + dataSource.setInitialPoolSize(5); + dataSource.setMinPoolSize(5); + dataSource.setMaxPoolSize(10); + return dataSource; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java new file mode 100644 index 0000000000..49b998bfb9 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/controller/BookstoreController.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.oracle.pooling.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.spring.oracle.pooling.entity.Book; +import com.baeldung.spring.oracle.pooling.exception.BookstoreException; +import com.baeldung.spring.oracle.pooling.repository.BookRepository; + +@RestController +@RequestMapping("/books") +public class BookstoreController { + + @Autowired + private BookRepository repository; + + @GetMapping(value = "/hello") + public String sayHello() { + return "Hello"; + } + + @GetMapping("/all") + public List findAll() { + return repository.findAll(); + } + + @PostMapping("/create") + public Book newBook(@RequestBody Book newBook) { + return repository.save(newBook); + } + + @GetMapping("/get/{id}") + public Book findOne(@PathVariable Long id) throws BookstoreException { + return repository.findById(id) + .orElseThrow(BookstoreException::new); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java new file mode 100644 index 0000000000..fb2c3fcf6a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.oracle.pooling.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + public Book() { + } + + public Book(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Book [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java new file mode 100644 index 0000000000..d2fb399ab3 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/exception/BookstoreException.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.oracle.pooling.exception; + +public class BookstoreException extends Exception{ + + /** + * + */ + private static final long serialVersionUID = 1L; + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java new file mode 100644 index 0000000000..a50a1b24a4 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/repository/BookRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.oracle.pooling.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.spring.oracle.pooling.entity.Book; + +public interface BookRepository extends JpaRepository{ + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties new file mode 100644 index 0000000000..9a1c7fc89d --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/application-oracle-pooling-basic.properties @@ -0,0 +1,27 @@ +logging.level.root=INFO + +# OracleDB connection settings +spring.datasource.url=jdbc:oracle:thin:@//localhost:11521/ORCLPDB1 +spring.datasource.username=books +spring.datasource.password=books +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +# Comment this line for standard Spring Boot default choosing algorithm +#spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource + +# HikariCP settings +spring.datasource.hikari.minimumIdle=5 +spring.datasource.hikari.maximumPoolSize=20 +spring.datasource.hikari.idleTimeout=30000 +spring.datasource.hikari.maxLifetime=2000000 +spring.datasource.hikari.connectionTimeout=30000 +spring.datasource.hikari.poolName=HikariPoolBooks + +# Tomcat settings +spring.datasource.tomcat.maxActive=15 +spring.datasource.tomcat.minIdle=5 + +# JPA settings +spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect +spring.jpa.hibernate.use-new-id-generator-mappings=false +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml b/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml index 8b13789179..4b792fd5dc 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/application.yml @@ -1 +1,9 @@ - +# Available profiles +# - none for no profile +# - oracle-pooling-basic - Oracle database with HikariCP. Loads configuration from application-oracle-pooling-basic.properties +# - oracle - Uses OracleDataSource. This profile also needs "oracle-pooling-basic" +# - oracle-ucp - Uses PoolDataSource. This profile also needs "oracle-pooling-basic" +# - c3p0 - Uses ComboPooledDataSource. This profile also needs "oracle-pooling-basic" +spring: + profiles: + active: none \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java index e4b623ee2b..93083f6c4c 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java @@ -5,10 +5,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import org.jdbi.v3.core.Jdbi; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -24,7 +22,7 @@ import com.baeldung.boot.jdbi.service.CarMakerService; import lombok.extern.slf4j.Slf4j; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = {SpringBootJdbiApplication.class, JdbiConfiguration.class}) @Slf4j public class SpringBootJdbiApplicationUnitTest { diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java new file mode 100644 index 0000000000..5a2d3f2d29 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationC3P0LiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "c3p0"}) +public class SpringOraclePoolingApplicationC3P0LiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenC3p0Configuration_thenBuildsComboPooledDataSource() { + assertTrue(dataSource instanceof com.mchange.v2.c3p0.ComboPooledDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java new file mode 100644 index 0000000000..ab8fc1e121 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationHikariCPLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles("oracle-pooling-basic") +public class SpringOraclePoolingApplicationHikariCPLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenHikariCPConfiguration_thenBuildsHikariCP() { + assertTrue(dataSource instanceof com.zaxxer.hikari.HikariDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java new file mode 100644 index 0000000000..229375dadd --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "oracle"}) +public class SpringOraclePoolingApplicationOracleLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenOracleConfiguration_thenBuildsOracleDataSource() { + assertTrue(dataSource instanceof oracle.jdbc.pool.OracleDataSource); + } + +} diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java new file mode 100644 index 0000000000..4fb6aa6bae --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.oracle.pooling; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import javax.sql.DataSource; + +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; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringOraclePoolingApplication.class}) +@ActiveProfiles({"oracle-pooling-basic", "oracle-ucp"}) +public class SpringOraclePoolingApplicationOracleUCPLiveTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenOracleUCPConfiguration_thenBuildsOraclePoolDataSource() { + assertTrue(dataSource instanceof oracle.ucp.jdbc.PoolDataSource); + } + +} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java new file mode 100644 index 0000000000..7aef08b2ce --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/audit/AuditorAwareImpl.java @@ -0,0 +1,19 @@ +package com.baeldung.hibernate.audit; + +import java.util.Optional; + +import org.springframework.data.domain.AuditorAware; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +public class AuditorAwareImpl implements AuditorAware { + + @Override + public String getCurrentAuditor() { + return Optional.ofNullable(SecurityContextHolder.getContext()) + .map(e -> e.getAuthentication()) + .map(Authentication::getName) + .orElse(null); + } + +} diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java index b7cf0fadf2..6ae133ca7a 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -23,6 +23,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; +import com.baeldung.hibernate.audit.AuditorAwareImpl; import com.baeldung.persistence.dao.IBarAuditableDao; import com.baeldung.persistence.dao.IBarDao; import com.baeldung.persistence.dao.IFooAuditableDao; @@ -46,7 +47,7 @@ import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") -@EnableJpaAuditing +@EnableJpaAuditing(auditorAwareRef = "auditorProvider") @PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence" }) public class PersistenceConfig { @@ -58,6 +59,11 @@ public class PersistenceConfig { super(); } + @Bean("auditorProvider") + public AuditorAwareImpl auditorAwareImpl() { + return new AuditorAwareImpl(); + } + @Bean public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 8a03310048..878c4592f9 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -24,7 +24,11 @@ spring-context ${org.springframework.version} - + + org.springframework + spring-aspects + ${org.springframework.version} + org.hibernate @@ -128,12 +132,13 @@ - 5.1.6.RELEASE + 5.2.5.RELEASE - 5.4.2.Final - 6.0.6 - 2.1.6.RELEASE + 5.4.13.Final + 8.0.19 + 1.4.200 + 2.2.6.RELEASE 9.0.0.M26 1.1 4.2.1 diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java index 569971e311..80f3ff14c5 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java @@ -1,9 +1,7 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.sql.DataSource; - +import com.baeldung.persistence.service.FooService; +import com.google.common.base.Preconditions; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -23,16 +21,15 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.baeldung.hibernate.dao.FooDao; -import com.baeldung.jpa.dao.IFooDao; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.hibernate.dao" }, transactionManagerRef = "jpaTransactionManager") @EnableJpaAuditing @PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan({ "com.baeldung.persistence", "com.baeldung.hibernate.dao" }) +@ComponentScan(basePackages = { "com.baeldung.persistence.dao", "com.baeldung.jpa.dao" }) public class PersistenceConfig { @Autowired @@ -46,7 +43,7 @@ public class PersistenceConfig { public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + sessionFactory.setPackagesToScan("com.baeldung.persistence.model"); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; @@ -56,7 +53,7 @@ public class PersistenceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(restDataSource()); - emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + emf.setPackagesToScan("com.baeldung.persistence.model"); final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); emf.setJpaVendorAdapter(vendorAdapter); @@ -96,18 +93,15 @@ public class PersistenceConfig { } @Bean - public IFooDao fooHibernateDao() { - return new FooDao(); + public FooService fooService() { + return new FooService(); } private final Properties hibernateProperties() { 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.show_sql", "true"); - // hibernateProperties.setProperty("hibernate.format_sql", "true"); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); // Envers properties hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index 7d3a881827..06cae493c9 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -1,10 +1,6 @@ package com.baeldung.config; -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - +import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -21,7 +17,8 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import com.google.common.base.Preconditions; +import javax.sql.DataSource; +import java.util.Properties; @Configuration @EnableTransactionManagement @@ -43,7 +40,7 @@ public class PersistenceJPAConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + em.setPackagesToScan("com.baeldung.persistence.model"); final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); @@ -64,9 +61,9 @@ public class PersistenceJPAConfig { } @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + public PlatformTransactionManager transactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java index 4fbc8464bb..a6542c5cb1 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java @@ -1,16 +1,15 @@ package com.baeldung.jpa.dao; -import java.io.Serializable; -import java.util.List; - import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; +import java.io.Serializable; +import java.util.List; public abstract class AbstractJpaDAO { private Class clazz; - @PersistenceContext + @PersistenceContext(unitName = "entityManagerFactory") private EntityManager entityManager; public final void setClazz(final Class clazzToSet) { diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml index bbb61cb3e0..55546a862a 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml +++ b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml @@ -21,7 +21,7 @@ - + diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql index c86d35cdae..ef4460e267 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql +++ b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql @@ -3,5 +3,5 @@ CREATE TABLE EMPLOYEE ID int NOT NULL PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255), - ADDRESS varchar(255), + ADDRESS varchar(255) ); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties index b3cfd31f46..9ba4f7602a 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties +++ b/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties @@ -1,7 +1,7 @@ # jdbc.X jdbc.driverClassName=com.mysql.cj.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true -jdbc.eventGeneratedId=tutorialuser +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true&serverTimezone=UTC +jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql # hibernate.X diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java index 69ddbb9b9f..5874b3c643 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java @@ -1,25 +1,6 @@ package com.baeldung.spring.data.persistence.jpaquery; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.jpaquery.UserRepository; import com.baeldung.spring.data.persistence.model.User; import org.junit.After; import org.junit.Test; @@ -36,6 +17,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; +import javax.persistence.EntityManager; +import javax.persistence.Query; +import java.time.LocalDate; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @@ -283,7 +274,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); assertThat(usersSortByName.get(0) .getName()).isEqualTo(USER_NAME_ADAM); @@ -295,7 +286,7 @@ public class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); @@ -459,6 +450,8 @@ public class UserRepositoryCommon { userRepository.save(usr01); userRepository.save(usr02); + System.out.println(TimeZone.getDefault()); + List users = userRepository.findUsersWithGmailAddress(); assertEquals(1, users.size()); assertEquals(usr02, users.get(0)); diff --git a/pom.xml b/pom.xml index 99d0943582..02d1ab6cd2 100644 --- a/pom.xml +++ b/pom.xml @@ -387,7 +387,7 @@ bazel blade bootique - + cdi checker-plugin @@ -505,6 +505,7 @@ libraries-data-db libraries-data-io libraries-http + libraries-http-2 libraries-io libraries-primitive libraries-security @@ -806,7 +807,7 @@ jenkins/plugins jhipster - + jws libraries @@ -900,7 +901,7 @@ bazel blade bootique - + cdi checker-plugin @@ -1017,6 +1018,7 @@ libraries-data-db libraries-data-io libraries-http + libraries-http-2 libraries-io libraries-primitive libraries-security @@ -1202,6 +1204,7 @@ spring-mvc-views spring-mvc-webflow spring-mvc-xml + spring-mvc-crash spring-protobuf spring-quartz @@ -1302,7 +1305,7 @@ jenkins/plugins jhipster - + jws libraries diff --git a/quarkus-extension/quarkus-liquibase/deployment/pom.xml b/quarkus-extension/quarkus-liquibase/deployment/pom.xml index c85d986390..5c6b56e152 100644 --- a/quarkus-extension/quarkus-liquibase/deployment/pom.xml +++ b/quarkus-extension/quarkus-liquibase/deployment/pom.xml @@ -3,8 +3,8 @@ 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 - quarkus-liquibase-deployment - quarkus-liquibase-deployment + deployment + deployment com.baeldung.quarkus.liquibase @@ -58,4 +58,4 @@ 3.8.1 - \ No newline at end of file + diff --git a/quarkus-extension/quarkus-liquibase/pom.xml b/quarkus-extension/quarkus-liquibase/pom.xml index 9536561701..8ed6555ed7 100644 --- a/quarkus-extension/quarkus-liquibase/pom.xml +++ b/quarkus-extension/quarkus-liquibase/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.baeldung.quarkus.liquibase quarkus-liquibase-parent - quarkus-liquibase-parent + quarkus-liquibase pom @@ -23,4 +23,4 @@ 1.0.0.Final
- \ No newline at end of file + diff --git a/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-extension/quarkus-liquibase/runtime/pom.xml index 83f7c8d4cc..760e6ab719 100644 --- a/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - quarkus-liquibase-runtime - quarkus-liquibase-runtime + runtime + runtime com.baeldung.quarkus.liquibase @@ -70,4 +70,4 @@ 3.8.1 - \ No newline at end of file + diff --git a/spring-boot-modules/spring-boot-annotations/pom.xml b/spring-boot-modules/spring-boot-annotations/pom.xml index 9ad63214ef..59de83b4e5 100644 --- a/spring-boot-modules/spring-boot-annotations/pom.xml +++ b/spring-boot-modules/spring-boot-annotations/pom.xml @@ -24,6 +24,22 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + + + + + org.hibernate + hibernate-core + @@ -32,4 +48,5 @@ test + diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java new file mode 100644 index 0000000000..4719425663 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/ConditionalBeanConfiguration.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +import java.util.Properties; + +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ConditionalBeanConfiguration { + + @Conditional(HibernateCondition.class) + Properties additionalProperties() { + // application specific properties + return new Properties(); + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java new file mode 100644 index 0000000000..e87ed6cb47 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HealthCheckController.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthCheckController { + + private static final String STATUS = "UP"; + + @GetMapping("/health") + public ResponseEntity healthCheck() { + return ResponseEntity.ok(STATUS); + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java new file mode 100644 index 0000000000..e2d77cc5d0 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/HibernateCondition.java @@ -0,0 +1,15 @@ +package com.baeldung.annotations; + +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; + +public class HibernateCondition implements Condition { + + @Override + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + // application specific condition check + return true; + } + +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java new file mode 100644 index 0000000000..ba23267525 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/MySQLAutoconfiguration.java @@ -0,0 +1,59 @@ +package com.baeldung.annotations; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +@Configuration +@ConditionalOnClass(DataSource.class) +public class MySQLAutoconfiguration { + + @Bean + @ConditionalOnBean(name = "dataSource") + LocalContainerEntityManagerFactoryBean entityManagerFactory() throws IOException { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); + + final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + @ConditionalOnProperty(name = "usemysql", havingValue = "local") + DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); + dataSource.setUrl("jdbc:hsqldb:mem:testdb"); + dataSource.setUsername( "sa" ); + dataSource.setPassword( "" ); + return dataSource; + } + + @ConditionalOnResource(resources = "classpath:mysql.properties") + Properties additionalProperties() throws IOException { + final Properties additionalProperties = new Properties(); + + try (InputStream inputStream = new ClassPathResource("classpath:mysql.properties").getInputStream()) { + additionalProperties.load(inputStream); + } + + return additionalProperties; + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java new file mode 100644 index 0000000000..62f68bee29 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/WebApplicationSpecificConfiguration.java @@ -0,0 +1,13 @@ +package com.baeldung.annotations; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebApplicationSpecificConfiguration { + + @ConditionalOnWebApplication + HealthCheckController healthCheckController() { + return new HealthCheckController(); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index 41f26d51f7..e54f28837d 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.configurationproperties.ConfigProperties; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class }) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java new file mode 100644 index 0000000000..6e798672e7 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java @@ -0,0 +1,33 @@ +package com.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "database") +public class Database { + + private String url; + private String username; + private String password; + + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties index 2e06fad574..d4d1df7abc 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/application.properties @@ -1,4 +1,8 @@ management.endpoints.web.exposure.include=refresh spring.properties.refreshDelay=1000 spring.config.location=file:extra.properties -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true + +database.url=jdbc:postgresql:/localhost:5432/instance +database.username=foo +database.password=bar \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java new file mode 100644 index 0000000000..0b9bd797ae --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.configurationproperties; + +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.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.properties.ConfigPropertiesDemoApplication; +import com.baeldung.properties.Database; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) +@TestPropertySource("classpath:application.properties") +public class DatabasePropertiesIntegrationTest { + + @Autowired + private Database database; + + @Test + public void testDatabaseProperties() { + Assert.assertNotNull(database); + Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl()); + Assert.assertEquals("foo", database.getUsername()); + Assert.assertEquals("bar", database.getPassword()); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties index 2e06fad574..d4d1df7abc 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties @@ -1,4 +1,8 @@ management.endpoints.web.exposure.include=refresh spring.properties.refreshDelay=1000 spring.config.location=file:extra.properties -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true + +database.url=jdbc:postgresql:/localhost:5432/instance +database.username=foo +database.password=bar \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java index f20fba737a..40f5341e29 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/Application.java @@ -1,43 +1,22 @@ package com.baeldung.web.log.app; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; import org.springframework.context.annotation.PropertySource; import com.baeldung.web.log.config.CustomeRequestLoggingFilter; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; - @EnableAutoConfiguration @ComponentScan("com.baeldung.web.log") @PropertySource("application-log.properties") @SpringBootApplication -public class Application extends SpringBootServletInitializer { +public class Application { public static void main(final String[] args) { SpringApplication.run(Application.class, args); } - - @Override - public void onStartup(ServletContext container) throws ServletException { - - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.setConfigLocation("com.baeldung.web.log"); - container.addListener(new ContextLoaderListener(context)); - - ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context)); - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/"); - - container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher"); - } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java new file mode 100644 index 0000000000..f51bb52990 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/config/CustomWebAppInitializer.java @@ -0,0 +1,25 @@ +package com.baeldung.web.log.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.WebApplicationInitializer; + +public class CustomWebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + context.setConfigLocation("com.baeldung.web.log"); + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + + container.addFilter("customRequestLoggingFilter", CustomeRequestLoggingFilter.class).addMappingForServletNames(null, false, "dispatcher"); + } +} \ No newline at end of file diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index 10dacf99e8..a8500d50f2 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -79,6 +79,11 @@ modelmapper ${modelmapper.version} + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + diff --git a/spring-caching/pom.xml b/spring-caching/pom.xml index d33f24de1f..f56d3cf328 100644 --- a/spring-caching/pom.xml +++ b/spring-caching/pom.xml @@ -1,49 +1,67 @@ - - 4.0.0 - spring-caching - 0.1-SNAPSHOT - spring-caching - war + + 4.0.0 + spring-caching + 0.1-SNAPSHOT + spring-caching + war - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + - - - org.springframework - spring-context - - - org.springframework.boot - spring-boot-starter-cache - - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.ehcache - ehcache - - - org.springframework - spring-test - test - - + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework + spring-context + + + org.springframework.boot + spring-boot-starter-cache + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.ehcache + ehcache + + + org.springframework + spring-test + test + + + com.github.ben-manes.caffeine + caffeine + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + 3.5.2 + - - 3.5.2 - - \ No newline at end of file diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java index 714dc443e0..afa1d0ec99 100644 --- a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java @@ -3,9 +3,13 @@ package com.baeldung.caching.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; +//import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @EnableCaching +//to run any module like ehcache,caching or multiplecachemanager in local machine +//add it's package for ComponentScan like below +//@ComponentScan("com.baeldung.multiplecachemanager") public class CacheApplication { public static void main(String[] args) { diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java new file mode 100644 index 0000000000..3da4c23e28 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java @@ -0,0 +1,28 @@ +package com.baeldung.multiplecachemanager.bo; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.CustomerDetailRepository; + +@Component +public class CustomerDetailBO { + + @Autowired + private CustomerDetailRepository customerDetailRepository; + + @Cacheable(cacheNames = "customers") + public Customer getCustomerDetail(Integer customerId) { + return customerDetailRepository.getCustomerDetail(customerId); + } + + @Cacheable(cacheNames = "customerOrders", cacheManager = "alternateCacheManager") + public List getCustomerOrders(Integer customerId) { + return customerDetailRepository.getCustomerOrders(customerId); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java new file mode 100644 index 0000000000..390881167f --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java @@ -0,0 +1,25 @@ +package com.baeldung.multiplecachemanager.bo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.OrderDetailRepository; + +@Component +public class OrderDetailBO { + + @Autowired + private OrderDetailRepository orderDetailRepository; + + @Cacheable(cacheNames = "orders", cacheResolver = "cacheResolver") + public Order getOrderDetail(Integer orderId) { + return orderDetailRepository.getOrderDetail(orderId); + } + + @Cacheable(cacheNames = "orderprice", cacheResolver = "cacheResolver") + public double getOrderPrice(Integer orderId) { + return orderDetailRepository.getOrderPrice(orderId); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java new file mode 100644 index 0000000000..247a9b596b --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java @@ -0,0 +1,40 @@ +package com.baeldung.multiplecachemanager.config; + +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.cache.interceptor.CacheResolver; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Primary; + +import com.github.benmanes.caffeine.cache.Caffeine; + +@Configuration +@EnableCaching +public class MultipleCacheManagerConfig extends CachingConfigurerSupport { + + @Bean + //@Primary + public CacheManager cacheManager() { + CaffeineCacheManager cacheManager = new CaffeineCacheManager("customers", "orders"); + cacheManager.setCaffeine(Caffeine.newBuilder() + .initialCapacity(200) + .maximumSize(500) + .weakKeys() + .recordStats()); + return cacheManager; + } + + @Bean + public CacheManager alternateCacheManager() { + return new ConcurrentMapCacheManager("customerOrders", "orderprice"); + } + + @Bean + public CacheResolver cacheResolver() { + return new MultipleCacheResolver(alternateCacheManager(), cacheManager()); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java new file mode 100644 index 0000000000..1bd869d98e --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java @@ -0,0 +1,38 @@ +package com.baeldung.multiplecachemanager.config; + +import java.util.ArrayList; +import java.util.Collection; + +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.interceptor.CacheOperationInvocationContext; +import org.springframework.cache.interceptor.CacheResolver; + +public class MultipleCacheResolver implements CacheResolver { + + private final CacheManager simpleCacheManager; + + private final CacheManager caffeineCacheManager; + + private static final String ORDER_CACHE = "orders"; + + private static final String ORDER_PRICE_CACHE = "orderprice"; + + public MultipleCacheResolver(CacheManager simpleCacheManager, CacheManager caffeineCacheManager) { + this.simpleCacheManager = simpleCacheManager; + this.caffeineCacheManager = caffeineCacheManager; + + } + + @Override + public Collection resolveCaches(CacheOperationInvocationContext context) { + Collection caches = new ArrayList(); + if ("getOrderDetail".equals(context.getMethod() + .getName())) { + caches.add(caffeineCacheManager.getCache(ORDER_CACHE)); + } else { + caches.add(simpleCacheManager.getCache(ORDER_PRICE_CACHE)); + } + return caches; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java new file mode 100644 index 0000000000..17a73bb27a --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java @@ -0,0 +1,43 @@ +package com.baeldung.multiplecachemanager.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.multiplecachemanager.bo.CustomerDetailBO; +import com.baeldung.multiplecachemanager.bo.OrderDetailBO; +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; + +@RestController +public class MultipleCacheManagerController { + + @Autowired + private CustomerDetailBO customerDetailBO; + + @Autowired + private OrderDetailBO orderDetailBO; + + @GetMapping(value = "/getCustomer/{customerid}") + public Customer getCustomer(@PathVariable Integer customerid) { + return customerDetailBO.getCustomerDetail(customerid); + } + + @GetMapping(value = "/getCustomerOrders/{customerid}") + public List getCustomerOrders(@PathVariable Integer customerid) { + return customerDetailBO.getCustomerOrders(customerid); + } + + @GetMapping(value = "/getOrder/{orderid}") + public Order getOrder(@PathVariable Integer orderid) { + return orderDetailBO.getOrderDetail(orderid); + } + + @GetMapping(value = "/getOrderPrice/{orderid}") + public double getOrderPrice(@PathVariable Integer orderid) { + return orderDetailBO.getOrderPrice(orderid); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java new file mode 100644 index 0000000000..cfae15f4e9 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java @@ -0,0 +1,24 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Customer { + + private int customerId; + + private String customerName; + + public int getCustomerId() { + return customerId; + } + + public void setCustomerId(int customerId) { + this.customerId = customerId; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java new file mode 100644 index 0000000000..4131464981 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java @@ -0,0 +1,34 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Item { + + private int itemId; + + private String itemDesc; + + private double itemPrice; + + public int getItemId() { + return itemId; + } + + public void setItemId(int itemId) { + this.itemId = itemId; + } + + public String getItemDesc() { + return itemDesc; + } + + public void setItemDesc(String itemDesc) { + this.itemDesc = itemDesc; + } + + public double getItemPrice() { + return itemPrice; + } + + public void setItemPrice(double itemPrice) { + this.itemPrice = itemPrice; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java new file mode 100644 index 0000000000..15da60d6ea --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java @@ -0,0 +1,44 @@ +package com.baeldung.multiplecachemanager.entity; + +public class Order { + + private int orderId; + + private int itemId; + + private int quantity; + + private int customerId; + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public int getItemId() { + return itemId; + } + + public void setItemId(int itemId) { + this.itemId = itemId; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public int getCustomerId() { + return customerId; + } + + public void setCustomerId(int customerId) { + this.customerId = customerId; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java new file mode 100644 index 0000000000..aab011427d --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java @@ -0,0 +1,49 @@ +package com.baeldung.multiplecachemanager.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.stereotype.Repository; + +import com.baeldung.multiplecachemanager.entity.Customer; +import com.baeldung.multiplecachemanager.entity.Order; + +@Repository +public class CustomerDetailRepository { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public Customer getCustomerDetail(Integer customerId) { + String customerQuery = "select * from customer where customerid = ? "; + Customer customer = new Customer(); + jdbcTemplate.query(customerQuery, new Object[] { customerId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + customer.setCustomerId(rs.getInt("customerid")); + customer.setCustomerName(rs.getString("customername")); + } + }); + return customer; + } + + public List getCustomerOrders(Integer customerId) { + String customerOrderQuery = "select * from orderdetail where customerid = ? "; + List orders = new ArrayList(); + jdbcTemplate.query(customerOrderQuery, new Object[] { customerId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + Order order = new Order(); + order.setCustomerId(rs.getInt("customerid")); + order.setItemId(rs.getInt("orderid")); + order.setOrderId(rs.getInt("orderid")); + order.setQuantity(rs.getInt("quantity")); + orders.add(order); + } + }); + return orders; + } +} diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java new file mode 100644 index 0000000000..58c0968e48 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java @@ -0,0 +1,53 @@ +package com.baeldung.multiplecachemanager.repository; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.stereotype.Repository; + +import com.baeldung.multiplecachemanager.entity.Item; +import com.baeldung.multiplecachemanager.entity.Order; + +@Repository +public class OrderDetailRepository { + + @Autowired + private JdbcTemplate jdbcTemplate; + + public Order getOrderDetail(Integer orderId) { + String orderDetailQuery = "select * from orderdetail where orderid = ? "; + Order order = new Order(); + jdbcTemplate.query(orderDetailQuery, new Object[] { orderId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + order.setCustomerId(rs.getInt("customerid")); + order.setOrderId(rs.getInt("orderid")); + order.setItemId(rs.getInt("itemid")); + order.setQuantity(rs.getInt("quantity")); + } + }); + return order; + } + + public double getOrderPrice(Integer orderId) { + + String orderItemJoinQuery = "select * from ( select * from orderdetail where orderid = ? ) o left join item on o.itemid = ITEM.itemid"; + Order order = new Order(); + Item item = new Item(); + + jdbcTemplate.query(orderItemJoinQuery, new Object[] { orderId }, new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + order.setCustomerId(rs.getInt("customerid")); + order.setOrderId(rs.getInt("orderid")); + order.setItemId(rs.getInt("itemid")); + order.setQuantity(rs.getInt("quantity")); + item.setItemDesc("itemdesc"); + item.setItemId(rs.getInt("itemid")); + item.setItemPrice(rs.getDouble("price")); + } + }); + return order.getQuantity() * item.getItemPrice(); + } +} diff --git a/spring-caching/src/main/resources/application.properties b/spring-caching/src/main/resources/application.properties new file mode 100644 index 0000000000..ee7b5e62c0 --- /dev/null +++ b/spring-caching/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + +# Enabling H2 Console +spring.h2.console.enabled=true +spring.h2.console.path=/h2 diff --git a/spring-caching/src/main/resources/data.sql b/spring-caching/src/main/resources/data.sql new file mode 100644 index 0000000000..e4165ae71f --- /dev/null +++ b/spring-caching/src/main/resources/data.sql @@ -0,0 +1,7 @@ +INSERT INTO CUSTOMER VALUES(1001,'BAELDUNG'); + +INSERT INTO ITEM VALUES(10001,'ITEM1',50.0); +INSERT INTO ITEM VALUES(10002,'ITEM2',100.0); + +INSERT INTO ORDERDETAIL VALUES(300001,1001,10001,2); +INSERT INTO ORDERDETAIL VALUES(300002,1001,10002,5); \ No newline at end of file diff --git a/spring-caching/src/main/resources/schema.sql b/spring-caching/src/main/resources/schema.sql new file mode 100644 index 0000000000..5862499bc0 --- /dev/null +++ b/spring-caching/src/main/resources/schema.sql @@ -0,0 +1,19 @@ +CREATE TABLE CUSTOMER( + CUSTOMERID INT PRIMARY KEY, + CUSTOMERNAME VARCHAR(250) NOT NULL +); + +CREATE TABLE ITEM( +ITEMID INT PRIMARY KEY, +ITEMDESC VARCHAR(250), +PRICE DOUBLE +); + +CREATE TABLE ORDERDETAIL( +ORDERID INT PRIMARY KEY, +CUSTOMERID INT NOT NULL, +ITEMID INT NOT NULL, +QUANTITY INT, +FOREIGN KEY (customerid) references CUSTOMER(customerid), +FOREIGN KEY (itemid) references ITEM(itemid) +); \ No newline at end of file diff --git a/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java b/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java new file mode 100644 index 0000000000..e02e5da246 --- /dev/null +++ b/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.multiplecachemanager; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.caffeine.CaffeineCache; +import org.springframework.util.Assert; + +import com.baeldung.multiplecachemanager.bo.OrderDetailBO; +import com.baeldung.multiplecachemanager.entity.Order; +import com.baeldung.multiplecachemanager.repository.OrderDetailRepository; + +@SpringBootApplication +@SpringBootTest +public class MultipleCacheManagerIntegrationUnitTest { + + @MockBean + private OrderDetailRepository orderDetailRepository; + + @Autowired + private OrderDetailBO orderDetailBO; + + @Autowired + private CacheManager cacheManager; + + @Autowired + private CacheManager alternateCacheManager; + + @Test + public void givenCacheResolverIsConfigured_whenCallGetOrderDetail_thenDataShouldBeInCaffieneCacheManager() { + Integer key = 30001; + cacheManager.getCache("orders") + .evict(key); + Order order = new Order(); + order.setCustomerId(1001); + order.setItemId(10001); + order.setOrderId(30001); + order.setQuantity(2); + Mockito.when(orderDetailRepository.getOrderDetail(key)) + .thenReturn(order); + orderDetailBO.getOrderDetail(key); + org.springframework.cache.caffeine.CaffeineCache cache = (CaffeineCache) cacheManager.getCache("orders"); + Assert.notNull(cache.get(key) + .get(), "caffieneCache should have had the data"); + } + + @Test + public void givenCacheResolverIsConfigured_whenCallGetOrderPrice_thenDataShouldBeInAlternateCacheManager() { + Integer key = 30001; + alternateCacheManager.getCache("orderprice") + .evict(key); + Mockito.when(orderDetailRepository.getOrderPrice(key)) + .thenReturn(500.0); + orderDetailBO.getOrderPrice(key); + Cache cache = alternateCacheManager.getCache("orderprice"); + Assert.notNull(cache.get(key) + .get(), "alternateCache should have had the data"); + } +} diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index e20fe338c1..df529d7fb1 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/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.cloud - openfeign + spring-cloud-openfeign 0.0.1-SNAPSHOT - openfeign + spring-cloud-openfeign OpenFeign project for Spring Boot diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml index 441924f1d3..93255959e4 100644 --- a/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - SpringCloudTaskSink - SpringCloudTaskSink + springcloudtasksink + springcloudtasksink jar Demo project for Spring Boot diff --git a/spring-core-2/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java b/spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java similarity index 81% rename from spring-core-2/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java rename to spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java index dd396a653f..034386ade9 100644 --- a/spring-core-2/src/main/java/com/baeldung/spring/config/MainWebAppInitializer.java +++ b/spring-core-2/src/main/java/com/baeldung/spring/config/MyWebApplicationInitializer.java @@ -6,15 +6,12 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; -import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class MainWebAppInitializer implements WebApplicationInitializer +public class MyWebApplicationInitializer implements WebApplicationInitializer { /** @@ -22,7 +19,7 @@ public class MainWebAppInitializer implements WebApplicationInitializer */ @Override public void onStartup(final ServletContext sc) throws ServletException { - System.out.println("MainWebAppInitializer.onStartup()"); + System.out.println("MyWebApplicationInitializer.onStartup()"); // Create the 'root' Spring application context final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); diff --git a/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java index 60e9499d4b..1380e34ebd 100644 --- a/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java +++ b/spring-core-2/src/test/java/com/baeldung/profiles/SpringProfilesWithMavenPropertiesIntegrationTest.java @@ -16,7 +16,7 @@ public class SpringProfilesWithMavenPropertiesIntegrationTest { DatasourceConfig datasourceConfig; @Test - public void testSpringProfiles() { + public void setupDatasource() { Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig); } } \ No newline at end of file diff --git a/spring-mvc-crash/.gitignore b/spring-mvc-crash/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-crash/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-mvc-crash/README.md b/spring-mvc-crash/README.md new file mode 100644 index 0000000000..f158a947b6 --- /dev/null +++ b/spring-mvc-crash/README.md @@ -0,0 +1,11 @@ +## Spring MVC XML + +This module contains articles about Spring MVC with XML configuration + +### Relevant Articles: + +- [Getting Started with CRaSH](https://www.baeldung.com/jvm-crash-shell) + +## Spring MVC with XML Configuration Example Project + +- access a sample jsp page at: `http://localhost:8080/spring-mvc-crash/welcome.htm \ No newline at end of file diff --git a/spring-mvc-crash/pom.xml b/spring-mvc-crash/pom.xml new file mode 100644 index 0000000000..d23e18361b --- /dev/null +++ b/spring-mvc-crash/pom.xml @@ -0,0 +1,176 @@ + + + 4.0.0 + spring-mvc-crash + 0.1-SNAPSHOT + spring-mvc-xml + war + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + + javax.servlet + jstl + ${jstl.version} + runtime + + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + commons-io + commons-io + ${commons-io.version} + + + com.maxmind.geoip2 + geoip2 + ${geoip2.version} + + + com.fasterxml.jackson.core + jackson-databind + + + commons-logging + commons-logging + + + + + org.glassfish + javax.el + ${javax.el.version} + + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + + + org.crashub + crash.embed.spring + ${crash.version} + + + org.crashub + crash.cli + ${crash.version} + + + org.crashub + crash.connectors.telnet + ${crash.version} + + + log4j + log4j + + + + + + + org.codehaus.groovy + groovy + ${groovy.version} + + + + + spring-mvc-xml + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + + + + + + + 5.0.2.RELEASE + 1.5.10.RELEASE + + + 5.1.40 + + + 4.4.5 + 4.5.2 + + + 6.0.10.Final + 3.0.1-b08 + + + 19.0 + 2.8.0 + + + 1.6.1 + + 1.3.2 + 3.0.0-rc-3 + + + + diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java new file mode 100644 index 0000000000..cc60a1ff8f --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@ImportResource("classpath:webMvcConfig.xml") +@Configuration +@ComponentScan +public class ClientWebConfig implements WebMvcConfigurer { + + public ClientWebConfig() { + super(); + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java new file mode 100644 index 0000000000..55af23034f --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/ClientWebConfigJava.java @@ -0,0 +1,33 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@ComponentScan("com.baeldung.spring") +public class ClientWebConfigJava implements WebMvcConfigurer { + + public ClientWebConfigJava() { + super(); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } + + @Bean + public MethodValidationPostProcessor methodValidationPostProcessor() { + return new MethodValidationPostProcessor(); + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java b/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java new file mode 100644 index 0000000000..526833611b --- /dev/null +++ b/spring-mvc-crash/src/main/java/com/baeldung/spring/controller/WelcomeController.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.AbstractController; + +public class WelcomeController extends AbstractController { + @Override + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { + + ModelAndView model = new ModelAndView("welcome"); + model.addObject("msg", "Welcome to Introduction to CRaSH article from Baeldung"); + + return model; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml b/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml new file mode 100644 index 0000000000..8a0671ca87 --- /dev/null +++ b/spring-mvc-crash/src/main/resources/contentManagementWebMvcConfig.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-crash/src/main/resources/logback.xml b/spring-mvc-crash/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/spring-mvc-crash/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/messages.properties b/spring-mvc-crash/src/main/resources/messages.properties new file mode 100644 index 0000000000..2a3cccf76c --- /dev/null +++ b/spring-mvc-crash/src/main/resources/messages.properties @@ -0,0 +1,2 @@ +required.name = Name is required! +NotEmpty.person.password = Password is required! \ No newline at end of file diff --git a/spring-mvc-crash/src/main/resources/webMvcConfig.xml b/spring-mvc-crash/src/main/resources/webMvcConfig.xml new file mode 100644 index 0000000000..4bdb405237 --- /dev/null +++ b/spring-mvc-crash/src/main/resources/webMvcConfig.xml @@ -0,0 +1,38 @@ + + + + + + + + + image/jpeg + image/png + + + + + + + + + + + + + + + + + + + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy new file mode 100644 index 0000000000..d66ab13d96 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message.groovy @@ -0,0 +1,14 @@ +import org.crsh.cli.Command; +import org.crsh.cli.Usage; +import org.crsh.cli.Option; + +class message { + + @Usage("show my own message") + @Command + Object main(@Usage("custom message") @Option(names=["m","message"]) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java new file mode 100644 index 0000000000..d1ead88024 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/commands/message2.java @@ -0,0 +1,14 @@ +import org.crsh.command.BaseCommand; +import org.crsh.cli.Usage; +import org.crsh.cli.Command; +import org.crsh.cli.Option; + +public class message2 extends BaseCommand { + @Usage("show my own message using java") + @Command + public Object main(@Usage("custom message") @Option(names = { "m", "message" }) String message) { + if (message == null) + message = "No message given..."; + return message; + } +} \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties new file mode 100644 index 0000000000..f9ad0d7cf6 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/crash.properties @@ -0,0 +1 @@ +crash.telnet.port=50001 diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties new file mode 100644 index 0000000000..99071d09ff --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/crash/telnet.properties @@ -0,0 +1,65 @@ +############################ +# Telnet daemon properties # +############################ + +##################### +# Terminals Section # +##################### + +# List of terminals available and defined below +terminals=vt100,ansi,windoof,xterm + +# vt100 implementation and aliases +term.vt100.class=net.wimpi.telnetd.io.terminal.vt100 +term.vt100.aliases=default,vt100-am,vt102,dec-vt100 + +# ansi implementation and aliases +term.ansi.class=net.wimpi.telnetd.io.terminal.ansi +term.ansi.aliases=color-xterm,xterm-color,vt320,vt220,linux,screen + +# windoof implementation and aliases +term.windoof.class=net.wimpi.telnetd.io.terminal.Windoof +term.windoof.aliases= + +# xterm implementation and aliases +term.xterm.class=net.wimpi.telnetd.io.terminal.xterm +term.xterm.aliases= + +################## +# Shells Section # +################## + +# List of shells available and defined below +shells=simple + +# shell implementations +shell.simple.class=org.crsh.telnet.term.TelnetHandler + +##################### +# Listeners Section # +##################### +listeners=std + + +# std listener specific properties + +#Basic listener and connection management settings (port is commented because CRaSH configures it) +# std.port=5000 +std.floodprotection=5 +std.maxcon=25 + + +# Timeout Settings for connections (ms) +std.time_to_warning=3600000 +std.time_to_timedout=60000 + +# Housekeeping thread active every 1 secs +std.housekeepinginterval=1000 + +std.inputmode=character + +# Login shell +std.loginshell=simple + +# Connection filter class +std.connectionfilter=none \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..46b159d984 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + welcomeController + welcomeController + + + + + + + + + + + + + + 5000 + + + + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp new file mode 100644 index 0000000000..ba8a836285 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/errorPage.jsp @@ -0,0 +1,10 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ page session="false"%> + + + Home + + +

${errorMsg}

+ + diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp new file mode 100644 index 0000000000..348ca652ff --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/view/welcome.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Welcome Page + + +

Welcome to ${msg}

+
+

+ Go to spring handler mappings homepage + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml b/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4a3d6cb321 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,70 @@ + + + Spring MVC XML Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + com.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + org.crsh.plugin.WebPluginLifeCycle + + + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + + + + ExampleOne + com.baeldung.jsp.ExampleOne + + + ExampleOne + /jsp/ExampleOne + + + ExampleThree + com.baeldung.jsp.ExampleThree + + + ExampleThree + /jsp/ExampleThree + + + + + + 10 + + + index.jsp + + + + /errors + + diff --git a/spring-mvc-crash/src/main/webapp/index.jsp b/spring-mvc-crash/src/main/webapp/index.jsp new file mode 100644 index 0000000000..149fc5fe0b --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/index.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC Examples + + + +

Spring MVC Examples

+ + + + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp b/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp new file mode 100644 index 0000000000..665eb86a30 --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/ExampleThree.jsp @@ -0,0 +1,10 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Java Binding Example + + +

Bound Value

+

You said: ${text}

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp b/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp new file mode 100644 index 0000000000..7b2247638d --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/ExampleTwo.jsp @@ -0,0 +1,13 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Java in Static Page Example + + +

Java in Static Page Example

+ <% String[] arr = {"What's up?", "Hello", "It's a nice day today!"}; + String greetings = arr[(int)(Math.random() * arr.length)]; + %> +

<%= greetings %>

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/main/webapp/jsp/index.jsp b/spring-mvc-crash/src/main/webapp/jsp/index.jsp new file mode 100644 index 0000000000..58c464125d --- /dev/null +++ b/spring-mvc-crash/src/main/webapp/jsp/index.jsp @@ -0,0 +1,12 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + JSP Examples + + +

Simple JSP Examples

+

Invoke HTML rendered by Servlet: here

+

Java in static page: here

+

Java injected by Servlet: here

+ + \ No newline at end of file diff --git a/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..62e34859ee --- /dev/null +++ b/spring-mvc-crash/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.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; + +import com.baeldung.spring.ClientWebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ClientWebConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..3623217130 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -0,0 +1,32 @@ +package com.baeldung.spring.web.config; + +import javax.servlet.MultipartConfigElement; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + private String TMP_FOLDER = "/tmp"; + private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; + + @Override + public void onStartup(ServletContext sc) throws ServletException { + + ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet( + new GenericWebApplicationContext())); + + appServlet.setLoadOnStartup(1); + + MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER, + MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); + + appServlet.setMultipartConfig(multipartConfigElement); + + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 96e300464b..768fda1c4a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -12,6 +12,7 @@ import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; @@ -121,4 +122,11 @@ public class WebConfig implements WebMvcConfigurer { public ExcelPOIHelper excelPOIHelper() { return new ExcelPOIHelper(); } + + @Bean(name = "multipartResolver") + public CommonsMultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(100000); + return multipartResolver; + } } \ No newline at end of file diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 685e7686b1..0adf127aaa 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -17,7 +17,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) -- [Getting Started with CRaSH](https://www.baeldung.com/jvm-crash-shell) ## Spring MVC with XML Configuration Example Project diff --git a/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java b/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java index 543ba76273..cafd9a38e3 100644 --- a/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java +++ b/spring-rest-http/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java @@ -72,7 +72,7 @@ public class FooMappingExamplesController { @RequestMapping(value = "/foos", produces = { "application/json", "application/xml" }) @ResponseBody - public String getFoosAsJsonFromREST() { + public String getFoosAsJsonFromBrowser() { return "Get some Foos with Header New"; } diff --git a/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..f85f9f3fb0 --- /dev/null +++ b/spring-security-modules/spring-security-mvc/src/main/java/com/baeldung/session/web/config/MainWebAppInitializer.java @@ -0,0 +1,16 @@ +package com.baeldung.session.web.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +import org.springframework.web.WebApplicationInitializer; + +public class MainWebAppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext sc) throws ServletException { + sc.getSessionCookieConfig().setHttpOnly(true); + sc.getSessionCookieConfig().setSecure(true); + } + +} diff --git a/spring-security-modules/spring-security-rest-custom/src/main/java/com/baeldung/web/controller/SecurityController.java b/spring-security-modules/spring-security-rest-custom/src/main/java/com/baeldung/web/controller/SecurityController.java index f35940f54c..ece442430f 100644 --- a/spring-security-modules/spring-security-rest-custom/src/main/java/com/baeldung/web/controller/SecurityController.java +++ b/spring-security-modules/spring-security-rest-custom/src/main/java/com/baeldung/web/controller/SecurityController.java @@ -18,7 +18,7 @@ public class SecurityController { @RequestMapping(value = "/username2", method = RequestMethod.GET) @ResponseBody - public String currentUserNameSimple(final Principal principal) { + public String currentUserName(final Principal principal) { return principal.getName(); } diff --git a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java index 731183bae2..27e3258efb 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java @@ -75,7 +75,53 @@ public class MockitoAnnotationUnitTest { Mockito.doReturn(100).when(spiedList).size(); assertEquals(100, spiedList.size()); } + + @Test + public void whenSpyingOnList_thenCorrect() { + List list = new ArrayList(); + List spyList = Mockito.spy(list); + + spyList.add("one"); + spyList.add("two"); + + Mockito.verify(spyList).add("one"); + Mockito.verify(spyList).add("two"); + + assertEquals(2, spyList.size()); + } + @Test + public void whenUsingTheSpyAnnotation_thenObjectIsSpied() { + spiedList.add("one"); + spiedList.add("two"); + + Mockito.verify(spiedList).add("one"); + Mockito.verify(spiedList).add("two"); + + assertEquals(2, spiedList.size()); + } + + @Test + public void whenStubASpy_thenStubbed() { + List list = new ArrayList(); + List spyList = Mockito.spy(list); + + assertEquals(0, spyList.size()); + + Mockito.doReturn(100).when(spyList).size(); + assertEquals(100, spyList.size()); + } + + @Test + public void whenCreateSpy_thenCreate() { + List spyList = Mockito.spy(new ArrayList<>()); + + spyList.add("one"); + Mockito.verify(spyList).add("one"); + + assertEquals(1, spyList.size()); + } + @Test public void whenNotUseCaptorAnnotation_thenCorrect() { final List mockList = Mockito.mock(List.class); diff --git a/twitter4j/pom.xml b/twitter4j/pom.xml index 6d98e2fe58..274b5c75c3 100644 --- a/twitter4j/pom.xml +++ b/twitter4j/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - Twitter4J - Twitter4J + twitter4J + twitter4J jar