diff --git a/apache-httpclient/pom.xml b/apache-httpclient/pom.xml index 3b178d4df8..f671c93cfc 100644 --- a/apache-httpclient/pom.xml +++ b/apache-httpclient/pom.xml @@ -63,11 +63,6 @@ ${wiremock.version} test - - org.apache.httpcomponents - httpclient - ${httpclient.version} - @@ -84,10 +79,9 @@ 5.6.1 3.3.1 - 5.2 - 5.2 - 5.2 - 4.5.14 + 5.2.2 + 5.2.2 + 5.2.2 diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java index 50cf1b7a64..7b818f871a 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -25,6 +25,7 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.nio.ssl.TlsStrategy; @@ -33,7 +34,6 @@ import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.reactor.IOReactorConfig; import org.apache.hc.core5.ssl.SSLContexts; import org.apache.hc.core5.ssl.TrustStrategy; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.junit.jupiter.api.Test; @@ -120,7 +120,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer { .build(); final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create() - .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) + .setHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSslContext(sslContext) .build(); diff --git a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java index fb597e46c8..eaf166a091 100644 --- a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java +++ b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -7,14 +7,14 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @Configuration @EnableWebSecurity -public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { +public class CustomWebSecurityConfigurerAdapter { @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint; @@ -27,8 +27,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda .authorities("ROLE_USER"); } - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/securityNone") @@ -40,6 +40,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + + return http.build(); } @Bean diff --git a/apache-kafka-2/pom.xml b/apache-kafka-2/pom.xml index d1f74e8aae..dedd5df602 100644 --- a/apache-kafka-2/pom.xml +++ b/apache-kafka-2/pom.xml @@ -55,14 +55,14 @@ com.fasterxml.jackson.core jackson-databind - ${jackson.databind.version} + ${jackson.databind.version} 5.7.0 2.8.0 - 1.15.3 + 1.19.3 1.15.3 2.15.2 diff --git a/apache-kafka/pom.xml b/apache-kafka/pom.xml index 494bc94961..22be7a83c6 100644 --- a/apache-kafka/pom.xml +++ b/apache-kafka/pom.xml @@ -182,7 +182,7 @@ 3.4.0 - 1.15.3 + 1.19.3 1.15.3 1.16.1 3.0.0 diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index adce036733..199b9a187e 100644 --- a/aws-modules/aws-dynamodb/pom.xml +++ b/aws-modules/aws-dynamodb/pom.xml @@ -1,7 +1,7 @@ + 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 aws-dynamodb 0.1.0-SNAPSHOT @@ -40,22 +40,6 @@ - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index b6326b6eb1..f04e84e14f 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -34,22 +34,6 @@ - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/aws-modules/aws-reactive/pom.xml b/aws-modules/aws-reactive/pom.xml index e6b50cadb2..22bd62c2ee 100644 --- a/aws-modules/aws-reactive/pom.xml +++ b/aws-modules/aws-reactive/pom.xml @@ -93,7 +93,6 @@ 2.2.1.RELEASE 2.17.283 - 1.18.20 \ No newline at end of file diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index e2bc04964a..9ba436b43f 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -39,27 +39,6 @@ - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - - - - 2.20.52 1.10.L001 diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index 06cea2f260..ce27a4f2e0 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -5,6 +5,13 @@ 4.0.0 aws-modules aws-modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + com.amazonaws @@ -15,12 +22,6 @@ pom - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - aws-app-sync aws-dynamodb diff --git a/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml b/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml index 975ad6f689..256b5e88ab 100644 --- a/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml +++ b/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml @@ -167,7 +167,6 @@ UTF-8 3.9 - 1.8 1.2.3 diff --git a/core-groovy-modules/core-groovy-2/pom.xml b/core-groovy-modules/core-groovy-2/pom.xml index de750daf0f..cc1d860ad1 100644 --- a/core-groovy-modules/core-groovy-2/pom.xml +++ b/core-groovy-modules/core-groovy-2/pom.xml @@ -13,6 +13,13 @@ 1.0.0-SNAPSHOT + + + groovy-plugins-release + https://groovy.jfrog.io/artifactory/plugins-release-local + + + org.apache.commons @@ -156,8 +163,8 @@ 1.1.3 3.4.2 3.8.1 - 3.7.0 - 3.0.8-01 + 3.9.0 + 3.0.9-03 diff --git a/core-java-modules/core-java-11-3/pom.xml b/core-java-modules/core-java-11-3/pom.xml index 22db9e62ab..0161f4dcca 100644 --- a/core-java-modules/core-java-11-3/pom.xml +++ b/core-java-modules/core-java-11-3/pom.xml @@ -45,7 +45,7 @@ 11 11 - 2.14.1 + 2.16.0 2.10 diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml index 8165549d8c..ae61bdfad0 100644 --- a/core-java-modules/core-java-12/pom.xml +++ b/core-java-modules/core-java-12/pom.xml @@ -21,8 +21,4 @@ - - 17 - - \ No newline at end of file diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml index 52cf227583..b8ec8cfdb9 100644 --- a/core-java-modules/core-java-13/pom.xml +++ b/core-java-modules/core-java-13/pom.xml @@ -13,8 +13,4 @@ 0.0.1-SNAPSHOT - - 17 - - \ No newline at end of file diff --git a/core-java-modules/core-java-15/pom.xml b/core-java-modules/core-java-15/pom.xml index 3996c69fa4..e6193b4ea3 100644 --- a/core-java-modules/core-java-15/pom.xml +++ b/core-java-modules/core-java-15/pom.xml @@ -26,8 +26,4 @@ - - 17 - - \ No newline at end of file diff --git a/core-java-modules/core-java-17/README.md b/core-java-modules/core-java-17/README.md index 4b1125532d..44a4e760e1 100644 --- a/core-java-modules/core-java-17/README.md +++ b/core-java-modules/core-java-17/README.md @@ -9,3 +9,4 @@ - [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17) - [Format Multiple ‘or’ Conditions in an If Statement in Java](https://www.baeldung.com/java-multiple-or-conditions-if-statement) - [Get All Record Fields and Its Values via Reflection](https://www.baeldung.com/java-reflection-record-fields-values) +- [Context-Specific Deserialization Filters in Java 17](https://www.baeldung.com/java-context-specific-deserialization-filters) diff --git a/core-java-modules/core-java-20/pom.xml b/core-java-modules/core-java-20/pom.xml index ad0a956b80..68c6ca4c93 100644 --- a/core-java-modules/core-java-20/pom.xml +++ b/core-java-modules/core-java-20/pom.xml @@ -3,19 +3,34 @@ 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-20 + com.baeldung.core-java-modules core-java-modules 0.0.1-SNAPSHOT - core-java-20 - - - 20 - 20 - UTF-8 - + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + org.assertj + assertj-core + 3.24.2 + test + + + org.mockito + mockito-junit-jupiter + 5.2.0 + test + + @@ -41,25 +56,10 @@ - - - jakarta.servlet - jakarta.servlet-api - 6.0.0 - provided - - - org.assertj - assertj-core - 3.24.2 - test - - - org.mockito - mockito-junit-jupiter - 5.2.0 - test - - + + 20 + 20 + UTF-8 + \ No newline at end of file diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Contact.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Contact.java new file mode 100644 index 0000000000..80df1393af --- /dev/null +++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Contact.java @@ -0,0 +1,5 @@ +package com.baeldung.deserialization; + +public record Contact(String email, String phone) { + // Constructor, getters, and other methods are automatically generated +} diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Person.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Person.java new file mode 100644 index 0000000000..38e3882668 --- /dev/null +++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Person.java @@ -0,0 +1,5 @@ +package com.baeldung.deserialization; + +public record Person(String name, int age, String address, Contact contact) { + // Constructor, getters, and other methods are automatically generated +} \ No newline at end of file diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java new file mode 100644 index 0000000000..1256505e0d --- /dev/null +++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.deserialization; + +import com.google.gson.Gson; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class DeserializationUnitTest { + + @Test + public void givenJsonString_whenDeserialized_thenPersonRecordCreated() { + String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\"}"; + + Person person = new Gson().fromJson(json, Person.class); + + assertEquals("John Doe", person.name()); + assertEquals(30, person.age()); + assertEquals("123 Main St", person.address()); + } + + @Test + public void givenNestedJsonString_whenDeserialized_thenPersonRecordCreated() { + String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\",\"contact\":{\"email\":\"john.doe@example.com\",\"phone\":\"555-1234\"}}"; + + Person person = new Gson().fromJson(json, Person.class); + + assertNotNull(person); + assertEquals("John Doe", person.name()); + assertEquals(30, person.age()); + assertEquals("123 Main St", person.address()); + + Contact contact = person.contact(); + + assertNotNull(contact); + assertEquals("john.doe@example.com", contact.email()); + assertEquals("555-1234", contact.phone()); + } +} diff --git a/core-java-modules/core-java-8-datetime-2/README.md b/core-java-modules/core-java-8-datetime-2/README.md index f7ada52da6..6fe450816e 100644 --- a/core-java-modules/core-java-8-datetime-2/README.md +++ b/core-java-modules/core-java-8-datetime-2/README.md @@ -8,4 +8,5 @@ - [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins) - [Round the Date in Java](https://www.baeldung.com/java-round-the-date) - [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max) +- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time) - [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java new file mode 100644 index 0000000000..eedd897e91 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.unixtime; + +import static org.junit.Assert.assertEquals; +import java.time.Instant; +import java.time.LocalDate; + +import java.time.Month; +import java.time.ZoneId; +import java.util.Date; + +import org.joda.time.DateTime; + +import org.junit.jupiter.api.Test; + +public class UnixTimeUnitTest { + + @Test + public void givenTimeUsingDateApi_whenConvertedToUnixTime_thenMatch() { + Date date = new Date(2023 - 1900, 1, 15, 0, 0, 0); + long expected = 1676419200; + long actual = date.getTime() / 1000L; + assertEquals(expected, actual); + } + + @Test + public void givenTimeUsingJodaTime_whenConvertedToUnixTime_thenMatch() { + DateTime dateTime = new DateTime(2023, 2, 15, 00, 00, 00, 0); + long expected = 1676419200; + long actual = dateTime.getMillis() / 1000L; + assertEquals(expected, actual); + } + + @Test + public void givenTimeUsingLocalDate_whenConvertedToUnixTime_thenMatch() { + LocalDate date = LocalDate.of(2023, Month.FEBRUARY, 15); + Instant instant = date.atStartOfDay().atZone(ZoneId.of("UTC")).toInstant(); + long expected = 1676419200; + long actual = instant.getEpochSecond(); + assertEquals(expected, actual); + } + +} diff --git a/core-java-modules/core-java-arrays-convert/README.md b/core-java-modules/core-java-arrays-convert/README.md index 2e34829525..118d8e00ed 100644 --- a/core-java-modules/core-java-arrays-convert/README.md +++ b/core-java-modules/core-java-arrays-convert/README.md @@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java - [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset) - [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array) - [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array) +- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char) diff --git a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteToCharArrayUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteToCharArrayUnitTest.java new file mode 100644 index 0000000000..c62520cedc --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteToCharArrayUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.array.conversions; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertArrayEquals; + +public class ByteToCharArrayUnitTest { + public static byte[] byteArray = {65, 66, 67, 68}; + public static char[] expected = {'A', 'B', 'C', 'D'}; + + @Test + public void givenByteArray_WhenUsingStandardCharsets_thenConvertToCharArray() { + char[] charArray = new String(byteArray, StandardCharsets.UTF_8).toCharArray(); + assertArrayEquals(expected, charArray); + } + + @Test + public void givenByteArray_WhenUsingSUsingStreams_thenConvertToCharArray() throws IOException { + ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray); + InputStreamReader reader = new InputStreamReader(inputStream); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + int data; + while ((data = reader.read()) != -1) { + char ch = (char) data; + outputStream.write(ch); + } + char[] charArray = outputStream.toString().toCharArray(); + assertArrayEquals(expected, charArray); + } + + @Test + public void givenByteArray_WhenUsingCharBuffer_thenConvertToCharArray() { + ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray); + CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer); + char[] charArray = new char[charBuffer.remaining()]; + charBuffer.get(charArray); + assertArrayEquals(expected, charArray); + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml index 52787cc0c9..265577f75e 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced/pom.xml @@ -57,7 +57,7 @@ - + 11 diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md index acee8154f7..c9fce58ac2 100644 --- a/core-java-modules/core-java-collections-5/README.md +++ b/core-java-modules/core-java-collections-5/README.md @@ -10,4 +10,5 @@ - [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue) - [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide) - [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray) +- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-4) diff --git a/core-java-modules/core-java-collections-conversions-2/pom.xml b/core-java-modules/core-java-collections-conversions-2/pom.xml index da6b6a564a..7723daa6db 100644 --- a/core-java-modules/core-java-collections-conversions-2/pom.xml +++ b/core-java-modules/core-java-collections-conversions-2/pom.xml @@ -43,7 +43,6 @@ 0.10.3 - 11 3.2.0 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml index b8832df357..c11781eeda 100644 --- a/core-java-modules/core-java-collections-list-5/pom.xml +++ b/core-java-modules/core-java-collections-list-5/pom.xml @@ -39,7 +39,7 @@ org.projectlombok lombok - 1.18.26 + ${lombok.version} provided @@ -67,7 +67,7 @@ 1.21 2.2 2.10.1 - 2.15.2 + 2.16.0 20230618 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml index 8c35dcee6e..a0cdc07644 100644 --- a/core-java-modules/core-java-collections-maps-6/pom.xml +++ b/core-java-modules/core-java-collections-maps-6/pom.xml @@ -13,14 +13,11 @@ 0.0.1-SNAPSHOT - - 5.2.5.RELEASE - com.fasterxml.jackson.core jackson-databind - 2.13.1 + 2.16.0 org.openjdk.jmh @@ -40,7 +37,7 @@ junit junit - 4.13.1 + ${junit.version} test @@ -51,4 +48,8 @@ + + 5.2.5.RELEASE + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index a62bdda7af..73b36394a3 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -4,4 +4,7 @@ - [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv) - [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair) - [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file) -- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) \ No newline at end of file +- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound) +- [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values) +- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) diff --git a/core-java-modules/core-java-collections-maps-7/pom.xml b/core-java-modules/core-java-collections-maps-7/pom.xml index a05b1b3528..bd355bea1e 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -1,15 +1,11 @@ + 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-collections-maps-7 core-java-collections-maps-7 jar - - 2.10.1 - 1.5 - core-java-modules @@ -38,6 +34,16 @@ guava 32.1.2-jre + + org.openjdk.jmh + jmh-core + 1.37 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.37 + @@ -53,4 +59,10 @@ + + + 2.10.1 + 1.5 + + diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/BenchmarkMapMethods.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethods.java similarity index 99% rename from core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/BenchmarkMapMethods.java rename to core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethods.java index eca028efe4..563b2ffdae 100644 --- a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/BenchmarkMapMethods.java +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethods.java @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.map.incrementmapkey; import java.util.HashMap; import java.util.Map; diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethodsJMH.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethodsJMH.java new file mode 100644 index 0000000000..4ddf3886e9 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethodsJMH.java @@ -0,0 +1,68 @@ +package com.baeldung.map.incrementmapkey; + +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; + +@State(Scope.Benchmark) +public class BenchmarkMapMethodsJMH { + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchMarkGuavaMap() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingAtomicMap(getString()); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchContainsKeyMap() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingContainsKey(getString()); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchMarkComputeMethod() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingCompute(getString()); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchMarkMergeMethod() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingMerge(getString()); + } + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + + private String getString() { + return + "Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n" + + "\n" + + "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n" + + "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n" + + "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n" + + "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n" + + "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n" + + "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n" + + "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n" + + "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe."; + } +} diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/IncrementMapValueWays.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/IncrementMapValueWays.java similarity index 98% rename from core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/IncrementMapValueWays.java rename to core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/IncrementMapValueWays.java index 70b3c6c54d..e15b3aae8e 100644 --- a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/IncrementMapValueWays.java +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/IncrementMapValueWays.java @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.map.incrementmapkey; import java.util.HashMap; import java.util.Map; diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java new file mode 100644 index 0000000000..8fd62cc20b --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java @@ -0,0 +1,141 @@ +package com.baeldung.map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import org.junit.jupiter.api.Test; + +class Player { + private String name; + private Integer score = 0; + + public Player(String name, Integer score) { + this.name = name; + this.score = score; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Player)) { + return false; + } + + Player player = (Player) o; + + if (!Objects.equals(name, player.name)) { + return false; + } + return Objects.equals(score, player.score); + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (score != null ? score.hashCode() : 0); + return result; + } + + public String getName() { + return name; + } + + public int getScore() { + return score; + } +} + +public class LinkedHashMapSortByValueUnitTest { + private static LinkedHashMap MY_MAP = new LinkedHashMap<>(); + + static { + MY_MAP.put("key a", 4); + MY_MAP.put("key b", 1); + MY_MAP.put("key c", 3); + MY_MAP.put("key d", 2); + MY_MAP.put("key e", 5); + } + + private static LinkedHashMap EXPECTED_MY_MAP = new LinkedHashMap<>(); + + static { + EXPECTED_MY_MAP.put("key b", 1); + EXPECTED_MY_MAP.put("key d", 2); + EXPECTED_MY_MAP.put("key c", 3); + EXPECTED_MY_MAP.put("key a", 4); + EXPECTED_MY_MAP.put("key e", 5); + } + + private static final LinkedHashMap PLAYERS = new LinkedHashMap<>(); + static { + PLAYERS.put("player a", new Player("Eric", 9)); + PLAYERS.put("player b", new Player("Kai", 7)); + PLAYERS.put("player c", new Player("Amanda", 20)); + PLAYERS.put("player d", new Player("Kevin", 4)); + } + + private static final LinkedHashMap EXPECTED_PLAYERS = new LinkedHashMap<>(); + + static { + EXPECTED_PLAYERS.put("player d", new Player("Kevin", 4)); + EXPECTED_PLAYERS.put("player b", new Player("Kai", 7)); + EXPECTED_PLAYERS.put("player a", new Player("Eric", 9)); + EXPECTED_PLAYERS.put("player c", new Player("Amanda", 20)); + } + + @Test + void whenUsingCollectionSort_thenGetExpectedResult() { + List> entryList = new ArrayList<>(MY_MAP.entrySet()); + Collections.sort(entryList, new Comparator>() { + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return o1.getValue() + .compareTo(o2.getValue()); + } + }); + + LinkedHashMap result = new LinkedHashMap<>(); + for (Map.Entry e : entryList) { + result.put(e.getKey(), e.getValue()); + } + assertEquals(EXPECTED_MY_MAP, result); + } + + @Test + void whenUsingEntrycomparingByValueAndFillAMap_thenGetExpectedResult() { + LinkedHashMap result = new LinkedHashMap<>(); + MY_MAP.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue()) + .forEachOrdered(entry -> result.put(entry.getKey(), entry.getValue())); + assertEquals(EXPECTED_MY_MAP, result); + } + + @Test + void whenUsingEntrycomparingByValueAndCollect_thenGetExpectedResult() { + LinkedHashMap result = MY_MAP.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue()) + .collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll); + assertEquals(EXPECTED_MY_MAP, result); + } + + @Test + void whenUsingEntrycomparingByValueAndComparator_thenGetExpectedResult() { + LinkedHashMap result = PLAYERS.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue(Comparator.comparing(Player::getScore))) + .collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll); + assertEquals(EXPECTED_PLAYERS, result); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/IncrementMapValueUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/incrementmapkey/IncrementMapValueUnitTest.java similarity index 97% rename from core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/IncrementMapValueUnitTest.java rename to core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/incrementmapkey/IncrementMapValueUnitTest.java index df4f2b787e..64b9e1155d 100644 --- a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/IncrementMapValueUnitTest.java +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/incrementmapkey/IncrementMapValueUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.map.incrementmapkey; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -9,6 +9,8 @@ import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; +import com.baeldung.map.incrementmapkey.IncrementMapValueWays; + public class IncrementMapValueUnitTest { @Test diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureUnitTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureUnitTest.java new file mode 100644 index 0000000000..5953c6d87a --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureUnitTest.java @@ -0,0 +1,150 @@ +package com.baeldung.concurrent.completablefuture; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class CompletableFutureUnitTest { + + @Test + public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() throws ExecutionException, InterruptedException { + Microservice mockMicroserviceA = mock(Microservice.class); + Microservice mockMicroserviceB = mock(Microservice.class); + + when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello")); + when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("World")); + + CompletableFuture resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB)); + + String result = resultFuture.get(); + assertEquals("HelloWorld", result); + } + + @Test + public void givenAsyncTask_whenProcessingAsyncWithException_thenReturnException() throws ExecutionException, InterruptedException { + Microservice mockMicroserviceA = mock(Microservice.class); + Microservice mockMicroserviceB = mock(Microservice.class); + + when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello")); + when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.failedFuture(new RuntimeException("Simulated Exception"))); + CompletableFuture resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB)); + // Use assertThrows to verify that the expected exception is thrown + ExecutionException exception = assertThrows(ExecutionException.class, resultFuture::get); + // Assert the exception message + assertEquals("Simulated Exception", exception.getCause() + .getMessage()); + } + + @Test + public void givenAsyncTask_whenProcessingAsyncWithTimeout_thenHandleTimeoutException() throws ExecutionException, InterruptedException { + Microservice mockMicroserviceA = mock(Microservice.class); + Microservice mockMicroserviceB = mock(Microservice.class); + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor)); + Executor delayedExecutor2 = CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS); + when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "World", delayedExecutor2)); + CompletableFuture resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB)); + assertThrows(TimeoutException.class, () -> resultFuture.get(300, TimeUnit.MILLISECONDS)); + } + + @Test + public void givenCompletableFuture_whenCompleted_thenStateIsDone() { + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor); + CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> " World"); + CompletableFuture cf3 = CompletableFuture.supplyAsync(() -> "!"); + CompletableFuture[] cfs = new CompletableFuture[] { cf1, cf2, cf3 }; + + CompletableFuture allCf = CompletableFuture.allOf(cfs); + + assertFalse(allCf.isDone()); + allCf.join(); + String result = Arrays.stream(cfs) + .map(CompletableFuture::join) + .collect(Collectors.joining()); + + assertFalse(allCf.isCancelled()); + assertTrue(allCf.isDone()); + assertFalse(allCf.isCompletedExceptionally()); + assertEquals(result, "Hello World!"); + } + + @Test + public void givenCompletableFuture_whenCompletedWithException_thenStateIsCompletedExceptionally() throws ExecutionException, InterruptedException { + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor); + CompletableFuture cf2 = CompletableFuture.failedFuture(new RuntimeException("Simulated Exception")); + CompletableFuture cf3 = CompletableFuture.supplyAsync(() -> "!"); + CompletableFuture[] cfs = new CompletableFuture[] { cf1, cf2, cf3 }; + + CompletableFuture allCf = CompletableFuture.allOf(cfs); + + assertFalse(allCf.isDone()); + assertFalse(allCf.isCompletedExceptionally()); + + // Exception is expected, assert the cause + CompletionException exception = assertThrows(CompletionException.class, allCf::join); + + assertEquals("Simulated Exception", exception.getCause() + .getMessage()); + assertTrue(allCf.isCompletedExceptionally()); + assertTrue(allCf.isDone()); + assertFalse(allCf.isCancelled()); + } + + @Test + public void givenCompletableFuture_whenCancelled_thenStateIsCancelled() throws ExecutionException, InterruptedException { + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor); + CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> " World"); + CompletableFuture cf3 = CompletableFuture.supplyAsync(() -> "!"); + CompletableFuture[] cfs = new CompletableFuture[] { cf1, cf2, cf3 }; + CompletableFuture allCf = CompletableFuture.allOf(cfs); + assertFalse(allCf.isDone()); + assertFalse(allCf.isCompletedExceptionally()); + allCf.cancel(true); + assertTrue(allCf.isCancelled()); + assertTrue(allCf.isDone()); + } + + CompletableFuture processAsync(List microservices) { + List> dataFetchFutures = fetchDataAsync(microservices); + return combineResults(dataFetchFutures); + } + + private List> fetchDataAsync(List microservices) { + return microservices.stream() + .map(client -> client.retrieveAsync("")) + .collect(Collectors.toList()); + } + + private CompletableFuture combineResults(List> dataFetchFutures) { + return CompletableFuture.allOf(dataFetchFutures.toArray(new CompletableFuture[0])) + .thenApply(v -> dataFetchFutures.stream() + .map(future -> future.exceptionally(ex -> { + throw new CompletionException(ex); + }) + .join()) + .collect(Collectors.joining())); + } + + interface Microservice { + CompletableFuture retrieveAsync(String input); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-5/README.md b/core-java-modules/core-java-concurrency-advanced-5/README.md index ba845a7c4b..d991b6cc34 100644 --- a/core-java-modules/core-java-concurrency-advanced-5/README.md +++ b/core-java-modules/core-java-concurrency-advanced-5/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization) +- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture) diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java index dca36fe7cb..34e0a7522b 100644 --- a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java +++ b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java @@ -2,7 +2,7 @@ package com.baeldung.wait_synchronization; public class ConditionChecker { - private volatile Boolean jobIsDone; + private volatile boolean jobIsDone; private final Object lock = new Object(); public void ensureCondition() { @@ -21,4 +21,4 @@ public class ConditionChecker { lock.notify(); } } -} \ No newline at end of file +} diff --git a/core-java-modules/core-java-console/pom.xml b/core-java-modules/core-java-console/pom.xml index 8677b672ea..a761b2749e 100644 --- a/core-java-modules/core-java-console/pom.xml +++ b/core-java-modules/core-java-console/pom.xml @@ -159,7 +159,7 @@ - 3.0.0-M1 + 3.6.2 1.8 1.8 0.3.2 diff --git a/core-java-modules/core-java-datetime-conversion/README.md b/core-java-modules/core-java-datetime-conversion/README.md index d3a3dae728..f30a21f84c 100644 --- a/core-java-modules/core-java-datetime-conversion/README.md +++ b/core-java-modules/core-java-datetime-conversion/README.md @@ -10,3 +10,5 @@ This module contains articles about converting between Java date and time object - [Convert Between LocalDateTime and ZonedDateTime](https://www.baeldung.com/java-localdatetime-zoneddatetime) - [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format) - [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate) +- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long) +- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime) diff --git a/core-java-modules/core-java-documentation/pom.xml b/core-java-modules/core-java-documentation/pom.xml index be18af1b10..23443dd5ea 100644 --- a/core-java-modules/core-java-documentation/pom.xml +++ b/core-java-modules/core-java-documentation/pom.xml @@ -33,7 +33,7 @@ - 3.0.0-M1 + 3.6.2 1.8 1.8 diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml index 8632748baa..830b386fe2 100644 --- a/core-java-modules/core-java-io-2/pom.xml +++ b/core-java-modules/core-java-io-2/pom.xml @@ -61,7 +61,7 @@ - 3.0.0-M1 + 3.6.2 3.3.1 diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index faeddafd81..93c9289fdd 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -134,7 +134,7 @@ - 3.5.0 + 3.6.2 2.7.1 2.8.0 diff --git a/core-java-modules/core-java-ipc/pom.xml b/core-java-modules/core-java-ipc/pom.xml new file mode 100644 index 0000000000..b7b37afb1d --- /dev/null +++ b/core-java-modules/core-java-ipc/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-java-ipc + core-java-ipc + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + diff --git a/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/DirectoryLiveTest.java b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/DirectoryLiveTest.java new file mode 100644 index 0000000000..ca7b6d2a0e --- /dev/null +++ b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/DirectoryLiveTest.java @@ -0,0 +1,32 @@ +package com.baeldung.ipc; + +import org.junit.jupiter.api.Test; + +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchKey; +import java.nio.file.WatchEvent; +import java.nio.file.WatchService; + + +public class DirectoryLiveTest { + @Test + public void consumer() throws Exception { + WatchService watchService = FileSystems.getDefault().newWatchService(); + // Set this to an appropriate directory. + Path path = Paths.get("/tmp/ipc"); + + path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); + + WatchKey key; + while ((key = watchService.take()) != null) { + for (WatchEvent event : key.pollEvents()) { + // React to new file. + System.out.println(event); + } + key.reset(); + } + } +} diff --git a/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/JmxLiveTest.java b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/JmxLiveTest.java new file mode 100644 index 0000000000..8ac16fdfc3 --- /dev/null +++ b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/JmxLiveTest.java @@ -0,0 +1,52 @@ +package com.baeldung.ipc; + +import org.junit.jupiter.api.Test; + +import javax.management.JMX; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; +import java.lang.management.ManagementFactory; +import java.util.concurrent.TimeUnit; + +public class JmxLiveTest { + /* + * This test needs to be run with the following system properties defined: + * -Dcom.sun.management.jmxremote=true + * -Dcom.sun.management.jmxremote.port=1234 + * -Dcom.sun.management.jmxremote.authenticate=false + * -Dcom.sun.management.jmxremote.ssl=false + */ + @Test + public void consumer() throws Exception { + ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test"); + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + server.registerMBean(new IPCTest(), objectName); + + TimeUnit.MINUTES.sleep(50); + } + + @Test + public void producer() throws Exception { + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi"); + try (JMXConnector jmxc = JMXConnectorFactory.connect(url, null)) { + ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test"); + + IPCTestMBean mbeanProxy = JMX.newMBeanProxy(jmxc.getMBeanServerConnection(), objectName, IPCTestMBean.class, true); + mbeanProxy.sendMessage("Hello"); + } + } + + public interface IPCTestMBean { + void sendMessage(String message); + } + + class IPCTest implements IPCTestMBean { + @Override + public void sendMessage(String message) { + System.out.println("Received message: " + message); + } + } +} diff --git a/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/SocketsLiveTest.java b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/SocketsLiveTest.java new file mode 100644 index 0000000000..9b006c110e --- /dev/null +++ b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/SocketsLiveTest.java @@ -0,0 +1,38 @@ +package com.baeldung.ipc; + +import org.junit.jupiter.api.Test; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; + +public class SocketsLiveTest { + @Test + public void consumer() throws Exception { + try (ServerSocket serverSocket = new ServerSocket(1234)) { + Socket clientSocket = serverSocket.accept(); + + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + + String line; + while ((line = in.readLine()) != null) { + System.out.println("Received message: " + line); + } + } + } + + @Test + public void producer() throws Exception { + try (Socket clientSocket = new Socket("localhost", 1234)) { + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + + out.println("Hello"); + + String response = in.readLine(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index a46299c669..138827781e 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/pom.xml @@ -274,7 +274,7 @@ 4.6.1 1.1 - 3.0.0-M1 + 3.6.2 1.4.4 3.1.1 3.3.0 diff --git a/core-java-modules/core-java-lang-6/README.md b/core-java-modules/core-java-lang-6/README.md index a49564a16a..214409dd04 100644 --- a/core-java-modules/core-java-lang-6/README.md +++ b/core-java-modules/core-java-lang-6/README.md @@ -9,4 +9,5 @@ This module contains articles about core features in the Java language - [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample) - [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code) - [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects) +- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null) - [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables) diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java new file mode 100644 index 0000000000..bde7b44897 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java @@ -0,0 +1,14 @@ +package com.baeldung.staticfinal; + +import java.util.HashMap; + +public class Bike { + public static final int TIRE = 2; + public static final int PEDAL; + public static final HashMap PART = new HashMap<>(); + + static { + PEDAL = 5; + } + +} diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java new file mode 100644 index 0000000000..2201dae4d1 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.staticfinal; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BikeUnitTest { + + @Test + void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() { + assertEquals(2, Bike.TIRE); + } + + @Test + void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() { + assertEquals(5, Bike.PEDAL); + } + + @Test + void givenPartConstantObject_whenObjectStateChanged_thenCorrect() { + Bike.PART.put("seat", 1); + assertEquals(1, Bike.PART.get("seat")); + + Bike.PART.put("seat", 5); + assertEquals(5, Bike.PART.get("seat")); + } + + @Test + void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() { + assertEquals(3.141592653589793, Math.PI); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java index 38f5edec61..ee43af3eff 100644 --- a/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java +++ b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java @@ -26,13 +26,25 @@ public class Rectangle { this.topRight = topRight; } - public boolean isOverlapping(Rectangle other) { - // one rectangle is to the top of the other - if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) { + public boolean isOverlapping(Rectangle comparedRectangle) { + // one rectangle is to the top of the comparedRectangle + if (this.topRight.getY() < comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() > comparedRectangle.topRight.getY()) { return false; } - // one rectangle is to the left of the other - if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) { + // one rectangle is to the left of the comparedRectangle + if (this.topRight.getX() < comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() > comparedRectangle.topRight.getX()) { + return false; + } + return true; + } + + public boolean isOverlappingWithoutBorders(Rectangle comparedRectangle) { + // one rectangle is to the top of the comparedRectangle + if (this.topRight.getY() <= comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() >= comparedRectangle.topRight.getY()) { + return false; + } + // one rectangle is to the left of the comparedRectangle + if (this.topRight.getX() <= comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() >= comparedRectangle.topRight.getX()) { return false; } return true; diff --git a/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java index e4bb614b48..18186b43b1 100644 --- a/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java +++ b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java @@ -1,7 +1,8 @@ package com.baeldung.algorithms.rectanglesoverlap; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.junit.Test; public class RectangleUnitTest { @@ -36,4 +37,18 @@ public class RectangleUnitTest { assertFalse(rectangle1.isOverlapping(rectangle2)); } + @Test + public void givenAdjacentRectangles_whensOverlappingCalled_shouldReturnTrue() { +Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14)); +Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14)); +assertTrue(rectangle1.isOverlapping(rectangle2)); + } + + @Test + public void givenAdjacentRectangles_whensOverlappingWithoutBordersCalled_shouldReturnFalse() { + Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14)); + Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14)); + assertFalse(rectangle1.isOverlappingWithoutBorders(rectangle2)); + } + } diff --git a/core-java-modules/core-java-lang-oop-types-2/README.md b/core-java-modules/core-java-lang-oop-types-2/README.md index f46a1a3306..208e3b7fa7 100644 --- a/core-java-modules/core-java-lang-oop-types-2/README.md +++ b/core-java-modules/core-java-lang-oop-types-2/README.md @@ -10,3 +10,4 @@ This module contains articles about types in Java - [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list) - [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum) - [Implementing toString() on enums in Java](https://www.baeldung.com/java-enums-tostring) +- [Checking if an Object’s Type Is Enum](https://www.baeldung.com/java-check-object-enum) diff --git a/core-java-modules/core-java-lang-operators-2/README.md b/core-java-modules/core-java-lang-operators-2/README.md index e8b792e634..4b93f8d192 100644 --- a/core-java-modules/core-java-lang-operators-2/README.md +++ b/core-java-modules/core-java-lang-operators-2/README.md @@ -10,3 +10,4 @@ This module contains articles about Java operators - [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans) - [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives) - [What Does “––>” Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan) +- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon) diff --git a/core-java-modules/core-java-lang-operators-2/src/main/java/com/baeldung/colonexamples/ColonExamples.java b/core-java-modules/core-java-lang-operators-2/src/main/java/com/baeldung/colonexamples/ColonExamples.java new file mode 100644 index 0000000000..873e28c3f6 --- /dev/null +++ b/core-java-modules/core-java-lang-operators-2/src/main/java/com/baeldung/colonexamples/ColonExamples.java @@ -0,0 +1,178 @@ +package com.baeldung.colonexamples; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Examples of the different ways Java uses the colon (:) character. + */ +public class ColonExamples { + + private final static Logger LOG = LoggerFactory.getLogger(ColonExamples.class); + + public void example1_enhancedForLoop() { + + // Original style + for(int i = 0; i < 10; i++) { + // do something + } + + // Using enhanced for loop + int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; + for(int i : numbers) { + // do something + } + + // Using List instead of array + List numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); + for(Integer i : numbersList) { + // do something + } + } + + public void example2_switchStatement(String animal) { + + // Original style + if(animal.equals("cat")) { + System.out.println("meow"); + } + else if(animal.equals("lion")) { + System.out.println("roar"); + } + else if(animal.equals("dog") || animal.equals("seal")) { + System.out.println("bark"); + } + else { + System.out.println("unknown"); + } + + // Using switch statement + switch(animal) { + case "cat": + System.out.println("meow"); + break; + case "lion": + System.out.println("roar"); + break; + case "dog": + case "seal": + System.out.println("bark"); + break; + default: + System.out.println("unknown"); + } + } + + public void example3_labels() { + + // For loops without labels + for(int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (checkSomeCondition()) { + break; + } + } + } + + outterLoop: for(int i = 0; i < 10; i++) { + innerLoop: for (int j = 0; j < 10; j++) { + if (checkSomeCondition()) { + break outterLoop; + } + } + } + } + + public void example4_ternaryOperator() { + + // Original way using if/else + int x; + if(checkSomeCondition()) { + x = 1; + } + else { + x = 2; + } + + // Using ternary operator + x = checkSomeCondition() ? 1 : 2; + + // Using with other statements + boolean remoteCallResult = callRemoteApi(); + LOG.info(String.format( + "The result of the remote API call %s successful", + remoteCallResult ? "was" : "was not" + )); + } + + public void example5_methodReferences() { + // Original way without lambdas and method references + List names = Arrays.asList("ross", "joey", "chandler"); + List upperCaseNames = new ArrayList<>(); + for(String name : names) { + upperCaseNames.add(name.toUpperCase()); + } + + // Using method reference with stream map operation + List petNames = Arrays.asList("ross", "joey", "chandler"); + List petUpperCaseNames = petNames + .stream() + .map(String::toUpperCase) + .collect(Collectors.toList()); + + // Method reference with stream filter + List pets = Arrays.asList(new Cat(), new Dog(), new Parrot()); + List onlyDogs = pets + .stream() + .filter(Dog.class::isInstance) + .collect(Collectors.toList()); + + // Method reference with constructors + Set onlyDogsSet = pets + .stream() + .filter(Dog.class::isInstance) + .collect(Collectors.toCollection(TreeSet::new)); + } + + public void example6_asserttion() { + // Original way without assertions + Connection conn = getConnection(); + if(conn == null) { + throw new RuntimeException("Connection is null"); + } + + // Using assert keyword + assert getConnection() != null : "Connection is null"; + } + + private boolean checkSomeCondition() { + return new Random().nextBoolean(); + } + + private boolean callRemoteApi() { + return new Random().nextBoolean(); + } + + private Connection getConnection() { + return null; + } + + private static interface Animal { + + } + private static class Dog implements Animal { + + } + + private static class Cat implements Animal { + + } + + private static class Parrot implements Animal { + + } +} diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java index 6ba8ed024c..dc81a0290b 100644 --- a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java @@ -11,55 +11,55 @@ import static org.junit.jupiter.api.Assertions.*; public class InstanceOfUnitTest { @Test - void giveWhenInstanceIsCorrect_thenReturnTrue() { + void givenWhenInstanceIsCorrect_thenReturnTrue() { Ring ring = new Ring(); assertTrue(ring instanceof Round); } @Test - void giveWhenObjectIsInstanceOfType_thenReturnTrue() { + void givenWhenObjectIsInstanceOfType_thenReturnTrue() { Circle circle = new Circle(); assertTrue(circle instanceof Circle); } @Test - void giveWhenInstanceIsOfSubtype_thenReturnTrue() { + void givenWhenInstanceIsOfSubtype_thenReturnTrue() { Circle circle = new Circle(); assertTrue(circle instanceof Round); } @Test - void giveWhenTypeIsInterface_thenReturnTrue() { + void givenWhenTypeIsInterface_thenReturnTrue() { Circle circle = new Circle(); assertTrue(circle instanceof Shape); } @Test - void giveWhenTypeIsOfObjectType_thenReturnTrue() { + void givenWhenTypeIsOfObjectType_thenReturnTrue() { Thread thread = new Thread(); assertTrue(thread instanceof Object); } @Test - void giveWhenInstanceValueIsNull_thenReturnFalse() { + void givenWhenInstanceValueIsNull_thenReturnFalse() { Circle circle = null; assertFalse(circle instanceof Round); } @Test - void giveWhenComparingClassInDiffHierarchy_thenCompilationError() { + void givenWhenComparingClassInDiffHierarchy_thenCompilationError() { //assertFalse( circle instanceof Triangle); } @Test - void giveWhenStream_whenCastWithoutInstanceOfChk_thenGetException() { + void givenWhenStream_whenCastWithoutInstanceOfChk_thenGetException() { Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle()); assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList())); } @Test - void giveWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() { + void givenWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() { Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle()); List ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList()); assertEquals(2, ringList.size()); diff --git a/core-java-modules/core-java-networking-4/pom.xml b/core-java-modules/core-java-networking-4/pom.xml index cbe6356d0f..4b49359c8c 100644 --- a/core-java-modules/core-java-networking-4/pom.xml +++ b/core-java-modules/core-java-networking-4/pom.xml @@ -56,7 +56,7 @@ 1.7 - 1.15.4 + 1.16.2 \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-7/README.md b/core-java-modules/core-java-numbers-7/README.md new file mode 100644 index 0000000000..42a43fd1fd --- /dev/null +++ b/core-java-modules/core-java-numbers-7/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer) diff --git a/core-java-modules/core-java-numbers-7/pom.xml b/core-java-modules/core-java-numbers-7/pom.xml new file mode 100644 index 0000000000..dec3084108 --- /dev/null +++ b/core-java-modules/core-java-numbers-7/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + core-java-numbers-7 + core-java-numbers-7 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + com.google.guava + guava + ${guava.version} + + + + core-java-numbers-7 + + + src/main/resources + true + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalzero/BigDecimalZeroVsNewBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalzero/BigDecimalZeroVsNewBigDecimalUnitTest.java new file mode 100644 index 0000000000..a10a615e2f --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalzero/BigDecimalZeroVsNewBigDecimalUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.bigdecimalzero; + +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; + +import static org.junit.jupiter.api.Assertions.*; + +public class BigDecimalZeroVsNewBigDecimalUnitTest { + @Test + void whenComparingZeroAndNewBigDecimal_thenGetExpectedResult() { + BigDecimal bd1 = new BigDecimal("42.00"); + BigDecimal bd2 = new BigDecimal("42.0000"); + assertEquals(0, bd1.compareTo(bd2)); + + assertNotEquals(bd1, bd2); + + BigDecimal zero0 = new BigDecimal(0); + assertNotEquals(zero0, new BigDecimal("0.000")); + + BigDecimal zero = BigDecimal.ZERO; + assertEquals(zero, zero0); + } + + @Test + void whenCallingBigDecimalZero_thenAlwaysGetTheSameObject() { + BigDecimal z1 = BigDecimal.ZERO; + BigDecimal z2 = BigDecimal.ZERO; + assertSame(z1, z2); + } + + @Test + void whenCallingNewBigDecimal_thenAlwaysGetTheSameObject() { + BigDecimal z1 = new BigDecimal(0); + BigDecimal z2 = new BigDecimal(0); + assertNotSame(z1, z2); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/doubleisint/CheckDoubleIsAnIntegerUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/doubleisint/CheckDoubleIsAnIntegerUnitTest.java new file mode 100644 index 0000000000..90d2c52595 --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/doubleisint/CheckDoubleIsAnIntegerUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.doubleisint; + +import com.google.common.math.DoubleMath; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CheckDoubleIsAnIntegerUnitTest { + + boolean notNaNOrInfinity(double d) { + return !(Double.isNaN(d) || Double.isInfinite(d)); + } + + @Test + void whenConvertingToInt_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = notNaNOrInfinity(d1) && (int) d1 == d1; + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = notNaNOrInfinity(d2) && (int) d2 == d2; + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = notNaNOrInfinity(d3) && (int) d3 == d3; + assertTrue(!d3IsInteger); // <-- fails if exceeding Integer's range + } + + @Test + void whenUsingModuloOperator_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = notNaNOrInfinity(d1) && (d1 % 1) == 0; + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = notNaNOrInfinity(d2) && (d2 % 1) == 0; + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = notNaNOrInfinity(d3) && (d3 % 1) == 0; + assertTrue(d3IsInteger); + + } + + + @Test + void whenCheckingFloorOrCeilingValue_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = notNaNOrInfinity(d1) && Math.floor(d1) == d1; + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = notNaNOrInfinity(d2) && Math.floor(d2) == d2; + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = notNaNOrInfinity(d3) && Math.floor(d3) == d3; + assertTrue(d3IsInteger); + + } + + @Test + void whenUsingGuava_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = DoubleMath.isMathematicalInteger(d1); + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = DoubleMath.isMathematicalInteger(d2); + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = DoubleMath.isMathematicalInteger(d3); + assertTrue(d3IsInteger); + + boolean isInfinityInt = DoubleMath.isMathematicalInteger(Double.POSITIVE_INFINITY); + assertFalse(isInfinityInt); + + boolean isNanInt = DoubleMath.isMathematicalInteger(Double.NaN); + assertFalse(isNanInt); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-conversions/README.md b/core-java-modules/core-java-numbers-conversions/README.md index dead88f025..b5f02a9d47 100644 --- a/core-java-modules/core-java-numbers-conversions/README.md +++ b/core-java-modules/core-java-numbers-conversions/README.md @@ -4,3 +4,5 @@ - [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long) - [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float) - [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal) +- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer) +- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five) diff --git a/core-java-modules/core-java-numbers-conversions/pom.xml b/core-java-modules/core-java-numbers-conversions/pom.xml index d014675ead..43809e8453 100644 --- a/core-java-modules/core-java-numbers-conversions/pom.xml +++ b/core-java-modules/core-java-numbers-conversions/pom.xml @@ -27,7 +27,7 @@ junit junit - 4.13.2 + ${junit.version} test diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java new file mode 100644 index 0000000000..444f4931d3 --- /dev/null +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.negate; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.*; + +public class NegateIntUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(NegateIntUnitTest.class); + + @Test + void whenUsingUnaryMinusOperator_thenGetExpectedResult() { + int x = 42; + assertEquals(-42, -x); + + int z = 0; + assertEquals(0, -z); + + int n = -42; + assertEquals(42, -n); + } + + @Test + void whenUsingBitwiseComplementOperator_thenGetExpectedResult() { + int x = 42; + assertEquals(-42, ~x + 1); + + int z = 0; + assertEquals(0, ~z + 1); + + int n = -42; + assertEquals(42, ~n + 1); + } + + @Test + void givenIntMinValue_whenUsingUnaryMinusOperator_thenCannotGetExpectedResult() { + int min = Integer.MIN_VALUE; + LOG.info("The value of '-min' is: " + -min); + + assertTrue((-min) < 0); + } + + @Test + void givenIntMinValue_whenUsingBitwiseComplementOperator_thenCannotGetExpectedResult() { + int min = Integer.MIN_VALUE; + int result = ~min + 1; + LOG.info("The value of '~min + 1' is: " + result); + + assertTrue(result < 0); + } + + + @Test + void whenUsingUnaryMinusOperatorWithMinInt_thenGetExpectedResult() { + int x = 42; + assertEquals(-42, Math.negateExact(x)); + + int z = 0; + assertEquals(0, Math.negateExact(z)); + + int n = -42; + assertEquals(42, Math.negateExact(n)); + + int min = Integer.MIN_VALUE; + assertThrowsExactly(ArithmeticException.class, () -> Math.negateExact(min)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/roundnumbertonearestmultiple/RoundNumberToNearestMultipleUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/roundnumbertonearestmultiple/RoundNumberToNearestMultipleUnitTest.java new file mode 100644 index 0000000000..24090be343 --- /dev/null +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/roundnumbertonearestmultiple/RoundNumberToNearestMultipleUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.roundnumbertonearestmultiple; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class RoundNumberToNearestMultipleUnitTest { + + public static int originalNumber = 18; + public static int expectedRoundedNumber = 20; + public static int nearest = 5; + + @Test + public void givenNumber_whenUsingBasicMathOperations_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = (originalNumber % nearest == 0) ? originalNumber : ((originalNumber / nearest) + 1) * nearest; + assertEquals(expectedRoundedNumber, roundedNumber); + } + + @Test + public void givenNumber_whenUsingMathCeil_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = (int) (Math.ceil(originalNumber / (float) (nearest)) * nearest); + assertEquals(expectedRoundedNumber, roundedNumber); + } + + @Test + public void givenNumber_whenUsingMathRound_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = Math.round(originalNumber / (float) (nearest)) * nearest; + assertEquals(expectedRoundedNumber, roundedNumber); + } + + @Test + public void givenNumber_whenUsingMathFloor_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = (int) (Math.floor((double) (originalNumber + nearest / 2) / nearest) * nearest); + assertEquals(expectedRoundedNumber, roundedNumber); + } + +} diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java index 27bc750d8a..849f71dc03 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java @@ -23,7 +23,7 @@ public class AppUnitTest { soundRecorder.build(af); try { soundRecorder.start(); - Thread.sleep(20000); + Thread.sleep(5000); soundRecorder.stop(); } catch (InterruptedException ex) { fail("Exception: " + ex); diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java index c3f390d8ae..dae1a705ed 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java @@ -69,7 +69,7 @@ public class ProcessApiUnitTest { }); }); - Thread.sleep(10000); + Thread.sleep(5000); childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { @@ -100,7 +100,7 @@ public class ProcessApiUnitTest { private void waistCPU() throws NoSuchAlgorithmException { ArrayList randArr = new ArrayList(4096); SecureRandom sr = SecureRandom.getInstanceStrong(); - Duration somecpu = Duration.ofMillis(4200L); + Duration somecpu = Duration.ofMillis(2000L); Instant end = Instant.now().plus(somecpu); while (Instant.now().isBefore(end)) { // System.out.println(sr.nextInt()); diff --git a/core-java-modules/core-java-reflection-3/pom.xml b/core-java-modules/core-java-reflection-3/pom.xml index fa5fe897e0..e60652f1f2 100644 --- a/core-java-modules/core-java-reflection-3/pom.xml +++ b/core-java-modules/core-java-reflection-3/pom.xml @@ -1,7 +1,7 @@ + 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-reflection-3 core-java-reflection-3 diff --git a/core-java-modules/core-java-security-4/README.md b/core-java-modules/core-java-security-4/README.md index 236715713b..3c910e50be 100644 --- a/core-java-modules/core-java-security-4/README.md +++ b/core-java-modules/core-java-security-4/README.md @@ -5,4 +5,5 @@ This module contains articles about core Java Security ### Relevant Articles: - [Check if Certificate Is Self-Signed or CA-Signed With Java](https://www.baeldung.com/java-check-certificate-sign) - [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate) +- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias) - More articles: [[<-- prev]](/core-java-modules/core-java-security-3) diff --git a/core-java-modules/core-java-serialization/pom.xml b/core-java-modules/core-java-serialization/pom.xml index 63771d2da0..ad0a730514 100644 --- a/core-java-modules/core-java-serialization/pom.xml +++ b/core-java-modules/core-java-serialization/pom.xml @@ -177,7 +177,7 @@ 0.4 1.8.7 1.1 - 3.0.0-M1 + 3.6.2 4.3.20.RELEASE diff --git a/core-java-modules/core-java-streams-5/pom.xml b/core-java-modules/core-java-streams-5/pom.xml index e217271f4c..33cd69f761 100644 --- a/core-java-modules/core-java-streams-5/pom.xml +++ b/core-java-modules/core-java-streams-5/pom.xml @@ -48,6 +48,11 @@ guava ${guava.version} + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/firstmatchingelement/User.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/firstmatchingelement/User.java new file mode 100644 index 0000000000..cb29af529a --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/firstmatchingelement/User.java @@ -0,0 +1,21 @@ +package com.baeldung.streams.firstmatchingelement; + +public class User { + + private String userName; + private Integer userId; + + public User(Integer userId, String userName) { + this.userId = userId; + this.userName = userName; + } + + public String getUserName() { + return userName; + } + + public Integer getUserId() { + return userId; + } + +} diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java new file mode 100644 index 0000000000..074aec29d6 --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.findfirstnullpointerexception; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; + +import org.junit.Test; + +public class FindFirstNullPointerExceptionUnitTest { + + private final List inputs = Arrays.asList(null, "foo", "bar"); + + @Test(expected = NullPointerException.class) + public void givenStream_whenCallingFindFirst_thenThrowNullPointerException() { + Optional firstElement = inputs.stream() + .findFirst(); + } + + @Test + public void givenStream_whenUsingOfNullableBeforeFindFirst_thenCorrect() { + Optional firstElement = inputs.stream() + .map(Optional::ofNullable) + .findFirst() + .flatMap(Function.identity()); + + assertTrue(firstElement.isEmpty()); + } + + @Test + public void givenStream_whenUsingFilterBeforeFindFirst_thenCorrect() { + Optional firstNonNullElement = inputs.stream() + .filter(Objects::nonNull) + .findFirst(); + + assertTrue(firstNonNullElement.isPresent()); + } + +} diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java new file mode 100644 index 0000000000..db9415e94b --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.streams.firstmatchingelement; + + +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +import org.apache.commons.collections4.IterableUtils; +import org.junit.Test; + +import com.google.common.collect.Iterables; + +public class FirstMatchingElementUnitTest { + + private List userList = List.of(new User(1, "David"), new User(2, "John"), new User(3, "Roger"), new User(4, "John")); + private String searchName = "John"; + + @Test + public void whenUsingStream_thenFindFirstMatchingUserIndex() { + AtomicInteger counter = new AtomicInteger(-1); + int index = userList.stream() + .filter(user -> { + counter.getAndIncrement(); + return searchName.equals(user.getUserName()); + }) + .mapToInt(user -> counter.get()) + .findFirst() + .orElse(-1); + + assertEquals(1, index); + } + + @Test + public void whenUsingIntStream_thenFindFirstMatchingUserIndex() { + int index = IntStream.range(0, userList.size() - 1) + .filter(streamIndex -> searchName.equals(userList.get(streamIndex).getUserName())) + .findFirst() + .orElse(-1); + assertEquals(1, index); + } + + @Test + public void whenUsingTakeWhile_thenFindFirstMatchingUserIndex() { + long predicateIndex = userList.stream() + .takeWhile(user -> !user.getUserName().equals(searchName)) + .count(); + assertEquals(1, predicateIndex); + } + + @Test + public void whenUsingTakeWhile_thenFindIndexFromNoMatchingElement() { + List userList = List.of(new User(1, "David"), new User(2, "Vick"), new User(3, "Roger"), new User(4, "James")); + long predicateIndex = userList.stream() + .takeWhile(user -> !user.getUserName().equals(searchName)) + .count(); + assertEquals(4, predicateIndex); + } + + @Test + public void whenUsingGoogleGuava_thenFindFirstMatchingUserIndex() { + int index = Iterables.indexOf(userList, user -> searchName.equals(user.getUserName())); + assertEquals(1, index); + } + + @Test + public void whenUsingApacheCommons_thenFindFirstMatchingUserIndex() { + int index = IterableUtils.indexOf(userList, user -> searchName.equals(user.getUserName())); + assertEquals(1, index); + } +} diff --git a/core-java-modules/core-java-streams/src/test/java/com/baeldung/skipinputstream/SkipInputStreamUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/skipinputstream/SkipInputStreamUnitTest.java new file mode 100644 index 0000000000..a41e5642fe --- /dev/null +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/skipinputstream/SkipInputStreamUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.skipinputstream; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.Assert.assertArrayEquals; + +public class SkipInputStreamUnitTest { + @Test + public void givenInputStreamWithBytes_whenSkipBytes_thenRemainingBytes() throws IOException { + byte[] inputData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + InputStream inputStream = new ByteArrayInputStream(inputData); + + long bytesToSkip = 3; + long skippedBytes = inputStream.skip(bytesToSkip); + + assertArrayEquals(new byte[]{4, 5, 6, 7, 8, 9, 10}, readRemainingBytes(inputStream)); + + assert skippedBytes == bytesToSkip : "Incorrect number of bytes skipped"; + } + + private byte[] readRemainingBytes(InputStream inputStream) throws IOException { + byte[] buffer = new byte[inputStream.available()]; + int bytesRead = inputStream.read(buffer); + if (bytesRead == -1) { + throw new IOException("End of stream reached"); + } + return buffer; + } +} diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index 27071e5427..76f21aa726 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -44,10 +44,10 @@ commons-codec ${commons-codec.version} - - org.springframework - spring-core - ${spring-core.version} + + org.springframework + spring-core + ${spring-core.version} diff --git a/core-java-modules/core-java-string-operations-3/pom.xml b/core-java-modules/core-java-string-operations-3/pom.xml index 0558e71a35..59d14805a0 100644 --- a/core-java-modules/core-java-string-operations-3/pom.xml +++ b/core-java-modules/core-java-string-operations-3/pom.xml @@ -72,7 +72,7 @@ 5.3.9 3.6.3 6.1.1 - 2.11.1 + 2.16.0 3.1.0 diff --git a/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java index 145e9788e4..a99778201a 100644 --- a/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java +++ b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java @@ -87,7 +87,7 @@ public class VersionComparisonUnitTest { assertTrue(version1_1_maven.compareTo(version1_1_gradle) < 0); Version version1_1_snapshot = new Version(1, 1, 0, "snapshot", null, null); - assertEquals(0, version1_1.compareTo(version1_1_snapshot)); + assertEquals(1, version1_1.compareTo(version1_1_snapshot)); assertTrue(version1_1_snapshot.isSnapshot()); } diff --git a/core-java-modules/core-java-string-operations-7/README.md b/core-java-modules/core-java-string-operations-7/README.md index 2b9c4c25f3..a05485ccb9 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -5,3 +5,4 @@ - [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters) - [Create a Mutable String in Java](https://www.baeldung.com/java-mutable-string) - [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence) +- [Difference Between String isEmpty() and isBlank()](https://www.baeldung.com/java-string-isempty-vs-isblank) diff --git a/core-java-modules/core-java-string-operations-7/pom.xml b/core-java-modules/core-java-string-operations-7/pom.xml index a2c7036e34..33a74365bc 100644 --- a/core-java-modules/core-java-string-operations-7/pom.xml +++ b/core-java-modules/core-java-string-operations-7/pom.xml @@ -24,12 +24,6 @@ commons-text ${commons-text.version} - - org.liquibase - liquibase-core - 4.9.1 - test - org.junit.jupiter junit-jupiter @@ -39,7 +33,7 @@ org.liquibase liquibase-core - 4.9.1 + ${liquibase.core.version} test @@ -67,6 +61,7 @@ 11 3.13.0 1.10.0 + 4.25.0 \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/stringmaxlength/StringMaxLengthMain.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/stringmaxlength/StringMaxLengthMain.java new file mode 100644 index 0000000000..42d0c05582 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/stringmaxlength/StringMaxLengthMain.java @@ -0,0 +1,35 @@ +package com.baeldung.stringmaxlength; + +public class StringMaxLengthMain { + + public static void main(String[] args) { + displayRuntimeMaxStringLength(); + displayMaxStringLength(); + simulateStringOverflow(); + } + + public static void simulateStringOverflow() { + try { + int maxLength = Integer.MAX_VALUE; + char[] charArray = new char[maxLength]; + for (int i = 0; i < maxLength; i++) { + charArray[i] = 'a'; + } + String longString = new String(charArray); + System.out.println("Successfully created a string of length: " + longString.length()); + } catch (OutOfMemoryError e) { + System.err.println("Overflow error: Attempting to create a string longer than Integer.MAX_VALUE"); + e.printStackTrace(); + } + } + + public static void displayRuntimeMaxStringLength() { + long maxMemory = Runtime.getRuntime().maxMemory(); + System.out.println("Maximum String length based on available memory: " + (maxMemory)); + } + + public static void displayMaxStringLength() { + int maxStringLength = Integer.MAX_VALUE; + System.out.println("Maximum String length based on Integer.MAX_VALUE: " + maxStringLength); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java index a3f95b0181..408d7b1a63 100644 --- a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.centertext; -import liquibase.repackaged.org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.jupiter.api.Test; diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java new file mode 100644 index 0000000000..4d045fe318 --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java @@ -0,0 +1,64 @@ +package com.baeldung.stringbuffer; + +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 10000, iterations = 10) +@Warmup(batchSize = 1000, iterations = 10) +@State(Scope.Thread) +public class ComparePerformance { + + String strInitial = "springframework"; + String strFinal = ""; + String replacement = "java-"; + + @Benchmark + public String benchmarkStringConcatenation() { + strFinal = ""; + strFinal += strInitial; + return strFinal; + } + + @Benchmark + public StringBuffer benchmarkStringBufferConcatenation() { + StringBuffer stringBuffer = new StringBuffer(strFinal); + stringBuffer.append(strInitial); + return stringBuffer; + } + + @Benchmark + public String benchmarkStringReplacement() { + strFinal = strInitial.replaceFirst("spring", replacement); + return strFinal; + } + + @Benchmark + public StringBuffer benchmarkStringBufferReplacement() { + StringBuffer stringBuffer = new StringBuffer(strInitial); + stringBuffer.replace(0,6, replacement); + return stringBuffer; + } + + public static void main(String[] args) throws RunnerException { + Options options = new OptionsBuilder() + .include(ComparePerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/HashCode.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/HashCode.java new file mode 100644 index 0000000000..65f17263a9 --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/HashCode.java @@ -0,0 +1,24 @@ +package com.baeldung.stringbuffer; + +public class HashCode { + + public static long getHashCodeString(String string) { + return string.hashCode(); + } + + public static long getHashCodeSBuffer(StringBuffer strBuff) { + return strBuff.hashCode(); + } + + public static void main(String[] args) { + String str = "Spring"; + System.out.println("String HashCode pre concatenation :" + getHashCodeString(str)); + str += "Framework"; + System.out.println("String HashCode post concatenation :" + getHashCodeString(str)); + + StringBuffer sBuf = new StringBuffer("Spring"); + System.out.println("StringBuffer HashCode pre concatenation :" + getHashCodeSBuffer(sBuf)); + sBuf.append("Framework"); + System.out.println("StringBuffer HashCode post concatenation :" + getHashCodeSBuffer(sBuf)); + } +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java index 585d65d4be..aef7f81da2 100644 --- a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java @@ -17,7 +17,7 @@ public class StringIteratorTest { public void whenUseJavaForLoop_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; - String result = StringIterator.javaForLoop(input); + String result = StringIterator.javaforLoop(input); assertEquals(expectedOutput, result); } @@ -25,7 +25,7 @@ public class StringIteratorTest { public void whenUseForEachMethod_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; - String result = StringIterator.java8ForEach(input); + String result = StringIterator.java8forEach(input); assertEquals(expectedOutput, result); } diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/ComparePerformanceTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/ComparePerformanceTest.java new file mode 100644 index 0000000000..696c4bae6b --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/ComparePerformanceTest.java @@ -0,0 +1,32 @@ +package com.baeldung.stringbuffer; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + + +public class ComparePerformanceTest { + + ComparePerformance cp = new ComparePerformance(); + + @Test + public void whenStringConcatenated_thenResultAsExpected() { + assertThat(cp.benchmarkStringConcatenation()).isEqualTo("springframework"); + } + + @Test + public void whenStringBufferConcatenated_thenResultAsExpected() { + StringBuffer stringBuffer = new StringBuffer("springframework"); + assertThat(cp.benchmarkStringBufferConcatenation()).isEqualToIgnoringCase(stringBuffer); + } + + @Test + public void whenStringReplaced_thenResultAsExpected() { + assertThat(cp.benchmarkStringReplacement()).isEqualTo("java-framework"); + } + + @Test + public void whenStringBufferReplaced_thenResultAsExpected() { + StringBuffer stringBuffer = new StringBuffer("java-framework"); + assertThat(cp.benchmarkStringBufferReplacement()).isEqualToIgnoringCase(stringBuffer); + } +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/HashCodeTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/HashCodeTest.java new file mode 100644 index 0000000000..265c4e1e40 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/HashCodeTest.java @@ -0,0 +1,24 @@ +package com.baeldung.stringbuffer; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class HashCodeTest { + + String str = "Spring"; + StringBuffer sBuf = new StringBuffer("Spring"); + + @Test + public void whenStringConcat_thenHashCodeChanges() { + HashCode hc = new HashCode(); + + long initialStringHashCode = hc.getHashCodeString(str); + long initialSBufHashCode = hc.getHashCodeSBuffer(sBuf); + + str += "Framework"; + sBuf.append("Framework"); + + assertThat(initialStringHashCode).isNotEqualTo(hc.getHashCodeString(str)); + assertThat(initialSBufHashCode).isEqualTo(hc.getHashCodeSBuffer(sBuf)); + } +} diff --git a/core-java-modules/core-java-swing/pom.xml b/core-java-modules/core-java-swing/pom.xml new file mode 100644 index 0000000000..28228ebb29 --- /dev/null +++ b/core-java-modules/core-java-swing/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + core-java-string-swing + core-java-string-swing + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + 20 + 20 + UTF-8 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-swing/src/main/java/com/baeldung/customfont/CustomFonts.java b/core-java-modules/core-java-swing/src/main/java/com/baeldung/customfont/CustomFonts.java new file mode 100644 index 0000000000..28e0da84ae --- /dev/null +++ b/core-java-modules/core-java-swing/src/main/java/com/baeldung/customfont/CustomFonts.java @@ -0,0 +1,55 @@ +package com.baeldung.customfont; + +import javax.swing.*; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +public class CustomFonts { + public static void main(String[] args) { + usingCustomFonts(); + } + + public static void usingCustomFonts() { + final GraphicsEnvironment GE = GraphicsEnvironment.getLocalGraphicsEnvironment(); + final List AVAILABLE_FONT_FAMILY_NAMES = Arrays.asList(GE.getAvailableFontFamilyNames()); + try { + final List LIST = Arrays.asList( + new File("font/JetBrainsMono/JetBrainsMono-Thin.ttf"), + new File("font/JetBrainsMono/JetBrainsMono-Light.ttf"), + new File("font/Roboto/Roboto-Light.ttf"), + new File("font/Roboto/Roboto-Regular.ttf"), + new File("font/Roboto/Roboto-Medium.ttf") + ); + for (File LIST_ITEM : LIST) { + if (LIST_ITEM.exists()) { + Font FONT = Font.createFont(Font.TRUETYPE_FONT, LIST_ITEM); + if (!AVAILABLE_FONT_FAMILY_NAMES.contains(FONT.getFontName())) { + GE.registerFont(FONT); + } + } + } + } catch (FontFormatException | IOException exception) { + JOptionPane.showMessageDialog(null, exception.getMessage()); + } + + + JFrame frame = new JFrame("Custom Font Example"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setLayout(new FlowLayout()); + + JLabel label1 = new JLabel("TEXT1"); + label1.setFont(new Font("Roboto Medium", Font.PLAIN, 17)); + + JLabel label2 = new JLabel("TEXT2"); + label2.setFont(new Font("JetBrainsMono-Thin", Font.PLAIN, 17)); + + frame.add(label1); + frame.add(label2); + + frame.pack(); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-swing/target/classes/org/example/Main.class b/core-java-modules/core-java-swing/target/classes/org/example/Main.class new file mode 100644 index 0000000000..5914458bc4 Binary files /dev/null and b/core-java-modules/core-java-swing/target/classes/org/example/Main.class differ diff --git a/core-java-modules/core-java-uuid/README.md b/core-java-modules/core-java-uuid/README.md index bd7bd9d9da..a32c1ae04f 100644 --- a/core-java-modules/core-java-uuid/README.md +++ b/core-java-modules/core-java-uuid/README.md @@ -6,3 +6,4 @@ - [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string) - [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string) - [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids) +- [Generating Unique Positive long Using UUID in Java](https://www.baeldung.com/java-uuid-unique-long-generation) diff --git a/core-java-modules/core-java-uuid/pom.xml b/core-java-modules/core-java-uuid/pom.xml index d46fcd8a65..0a0835ca46 100644 --- a/core-java-modules/core-java-uuid/pom.xml +++ b/core-java-modules/core-java-uuid/pom.xml @@ -154,7 +154,7 @@ - 3.0.0-M1 + 3.6.2 diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java new file mode 100644 index 0000000000..eb3a511256 --- /dev/null +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java @@ -0,0 +1,83 @@ +package com.baeldung.uuid; + +import java.nio.ByteBuffer; +import java.security.SecureRandom; +import java.util.UUID; + +/** + * Methods are called by reflection in the unit test + */ +@SuppressWarnings("unused") +public class UUIDPositiveLongGenerator { + public long getLeastSignificantBits() { + return Math.abs(UUID.randomUUID().getLeastSignificantBits()); + } + + public long getMostSignificantBits() { + return Math.abs(UUID.randomUUID().getMostSignificantBits()); + } + + public long combineByteBuffer() { + UUID uuid = UUID.randomUUID(); + ByteBuffer bb = ByteBuffer.wrap(new byte[16]); + bb.putLong(uuid.getMostSignificantBits()); + bb.putLong(uuid.getLeastSignificantBits()); + bb.rewind(); + return Math.abs(bb.getLong()); + } + + public long combineBitwise() { + UUID uniqueUUID = UUID.randomUUID(); + long mostSignificantBits = uniqueUUID.getMostSignificantBits(); + long leastSignificantBits = uniqueUUID.getLeastSignificantBits(); + return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL)); + } + + public long combineDirect() { + UUID uniqueUUID = UUID.randomUUID(); + long mostSignificantBits = uniqueUUID.getMostSignificantBits(); + long leastSignificantBits = uniqueUUID.getLeastSignificantBits(); + return Math.abs(mostSignificantBits ^ (leastSignificantBits >> 1)); + } + + public long combinePermutation() { + UUID uuid = UUID.randomUUID(); + long mostSigBits = uuid.getMostSignificantBits(); + long leastSigBits = uuid.getLeastSignificantBits(); + byte[] uuidBytes = new byte[16]; + + for (int i = 0; i < 8; i++) { + uuidBytes[i] = (byte) (mostSigBits >>> (8 * (7 - i))); + uuidBytes[i + 8] = (byte) (leastSigBits >>> (8 * (7 - i))); + } + + long result = 0; + for (byte b : uuidBytes) { + result = (result << 8) | (b & 0xFF); + } + return Math.abs(result); + } + + public long combineWithSecureRandom() { + UUID uniqueUUID = UUID.randomUUID(); + SecureRandom secureRandom = new SecureRandom(); + long randomBits = secureRandom.nextLong(); + + long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ randomBits; + long leastSignificantBits = uniqueUUID.getLeastSignificantBits(); + + return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL)); + } + + public long combineWithNanoTime() { + UUID uniqueUUID = UUID.randomUUID(); + long nanoTime = System.nanoTime(); + + long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ nanoTime; + long leastSignificantBits = uniqueUUID.getLeastSignificantBits(); + + return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL)); + } + + +} diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java new file mode 100644 index 0000000000..a4d57b19c2 --- /dev/null +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.uuid; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UUIDPositiveLongGeneratorUnitTest { + + private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); + + private final Set uniqueValues = new HashSet<>(); + + @Test + void whenForeachMethods_thenRetryWhileNotUnique() throws Exception { + for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { + long uniqueValue; + do uniqueValue = (long) method.invoke(uuidLongGenerator); while (!isUnique(uniqueValue)); + assertThat(uniqueValue).isPositive(); + } + } + + @Test + void whenGivenLongValue_thenCheckUniqueness() { + long uniqueValue = generateUniqueLong(); + assertThat(uniqueValue).isPositive(); + } + + private long generateUniqueLong() { + long uniqueValue; + do uniqueValue = uuidLongGenerator.combineBitwise(); while (!isUnique(uniqueValue)); + return uniqueValue; + } + + private boolean isUnique(long value) { + // Implement uniqueness checking logic, for example, by checking in the database + return uniqueValues.add(value); + } + +} diff --git a/core-java-modules/core-java-uuid/src/test/resources/logback.xml b/core-java-modules/core-java-uuid/src/test/resources/logback.xml index 56af2d397e..a076f8db47 100644 --- a/core-java-modules/core-java-uuid/src/test/resources/logback.xml +++ b/core-java-modules/core-java-uuid/src/test/resources/logback.xml @@ -2,8 +2,7 @@ - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 27d84c742d..d20a1650b9 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -54,20 +54,21 @@ core-java-concurrency-simple core-java-datetime-string core-java-io-conversions-2 + core-java-ipc core-java-jpms core-java-lang-oop-constructors-2 core-java-methods core-java-networking-3 - core-java-os + core-java-perf-2 core-java-streams-4 core-java-streams-5 core-java-streams-collect core-java-streams-maps core-java-string-algorithms-3 - core-java-string-operations-3 + core-java-string-operations-4 - core-java-string-operations-5 + core-java-time-measurements core-java-annotations @@ -122,13 +123,13 @@ core-java-io core-java-io-2 core-java-io-3 - core-java-io-4 + core-java-io-5 core-java-io-apis core-java-io-apis-2 core-java-io-conversions core-java-jar - core-java-jndi + core-java-jvm core-java-jvm-2 core-java-jvm-3 @@ -143,11 +144,11 @@ core-java-lang-oop-constructors core-java-lang-oop-patterns core-java-lang-oop-generics - core-java-lang-oop-modifiers + core-java-lang-oop-types core-java-lang-oop-types-2 core-java-lang-oop-inheritance - core-java-lang-oop-methods + core-java-lang-oop-others core-java-lang-operators core-java-lang-operators-2 @@ -165,6 +166,7 @@ core-java-numbers-4 core-java-numbers-5 core-java-numbers-6 + core-java-numbers-7 core-java-optional core-java-perf core-java-properties @@ -183,7 +185,8 @@ core-java-string-algorithms core-java-string-algorithms-2 core-java-string-apis - core-java-string-apis-2 + + core-java-swing core-java-string-conversions core-java-string-conversions-2 core-java-string-conversions-3 @@ -223,5 +226,4 @@ - diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 875d8cdf85..aab19a166d 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -68,7 +68,6 @@ 0.9.1 4.3.5 - 1.18.20 \ No newline at end of file diff --git a/docker-modules/docker-caching/multi-module-caching/pom.xml b/docker-modules/docker-caching/multi-module-caching/pom.xml index bebfb85e8a..f2b52f246d 100644 --- a/docker-modules/docker-caching/multi-module-caching/pom.xml +++ b/docker-modules/docker-caching/multi-module-caching/pom.xml @@ -25,8 +25,6 @@ - UTF-8 - 1.8 32.1.3-jre diff --git a/docker-modules/pom.xml b/docker-modules/pom.xml index b4c5240718..4eeab746eb 100644 --- a/docker-modules/pom.xml +++ b/docker-modules/pom.xml @@ -24,8 +24,4 @@ docker-java-jar - - 11 - - \ No newline at end of file diff --git a/feign/pom.xml b/feign/pom.xml index edb55e7da5..127f6c490c 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -74,6 +74,17 @@ ${wire.mock.version} test + + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.0 + + + com.sun.xml.bind + jaxb-impl + 4.0.0 + runtime + @@ -85,7 +96,7 @@ org.codehaus.mojo jaxb2-maven-plugin - 2.5.0 + 3.1.0 xjc @@ -131,6 +142,7 @@ 3.8.0 3.1.2 2.33.2 + 4.0.0 \ No newline at end of file diff --git a/gradle-modules/gradle-7/README.md b/gradle-modules/gradle-7/README.md index fe05a4b9bc..c452ee8b33 100644 --- a/gradle-modules/gradle-7/README.md +++ b/gradle-modules/gradle-7/README.md @@ -5,4 +5,5 @@ - [Working With Multiple Repositories in Gradle](https://www.baeldung.com/java-gradle-multiple-repositories) - [Different Dependency Version Declarations in Gradle](https://www.baeldung.com/gradle-different-dependency-version-declarations) - [Generating Javadoc With Gradle](https://www.baeldung.com/java-gradle-javadoc) -- [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs) \ No newline at end of file +- [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs) +- [Gradle Proxy Configuration](https://www.baeldung.com/gradle-proxy-configuration) diff --git a/gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.jar b/gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..c1962a79e2 Binary files /dev/null and b/gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.jar differ diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index a0f2dd6514..e0488bf0b1 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -203,7 +203,6 @@ - 17 1.16.0 diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Animals.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Animals.java new file mode 100644 index 0000000000..1ad1014414 --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Animals.java @@ -0,0 +1,27 @@ +package com.baeldung.mismatchedinputexception; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Animals { + + private final int id; + private String name; + + + public Animals(@JsonProperty("id") int id, @JsonProperty("name")String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Book.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Book.java new file mode 100644 index 0000000000..28fe118ac5 --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.mismatchedinputexception; + +public class Book { + + private int id; + private String title; + + public Book(int id, String title) { + this.id = id; + this.title = title; + } + + public Book() { + } + + public int getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mismatchedinputexception/MismatchedinputExceptionUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mismatchedinputexception/MismatchedinputExceptionUnitTest.java new file mode 100644 index 0000000000..178ad1a8db --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mismatchedinputexception/MismatchedinputExceptionUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.mismatchedinputexception; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MismatchedinputExceptionUnitTest { + + @Test + void givenJsonString_whenDeserializingToJavaObjectWithImmutableField_thenIdIsCorrect() throws JsonProcessingException { + String jsonString = "{\"id\":10,\"name\":\"Dog\"}"; + ObjectMapper mapper = new ObjectMapper(); + Animals animal = mapper.readValue(jsonString, Animals.class); + assertEquals(animal.getId(),10); + } + + @Test + void givenJsonString_whenDeserializingToBook_thenIdIsCorrect() throws JsonProcessingException { + String jsonString = "{\"id\":\"10\",\"title\":\"Harry Potter\"}"; + ObjectMapper mapper = new ObjectMapper(); + Book book = mapper.readValue(jsonString, Book.class); + assertEquals(book.getId(),10); + } + + + @Test + void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException { + String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]"; + ObjectMapper mapper = new ObjectMapper(); + List book = mapper.readValue(jsonString, new TypeReference>(){}); + assertEquals(book.get(0).getTitle(),"Harry Potter"); + } + +} \ No newline at end of file diff --git a/jackson-modules/jackson-polymorphic-deserialization/pom.xml b/jackson-modules/jackson-polymorphic-deserialization/pom.xml index 0d88c19500..cbf67e5013 100644 --- a/jackson-modules/jackson-polymorphic-deserialization/pom.xml +++ b/jackson-modules/jackson-polymorphic-deserialization/pom.xml @@ -16,7 +16,7 @@ com.fasterxml.jackson.core jackson-core - ${jackson-core.version} + ${jackson.version} org.reflections @@ -36,7 +36,7 @@ - 2.15.2 + 2.16.0 0.9.11 diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index 3bf523bbfa..daa6504709 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -33,8 +33,7 @@ - 2.15.2 - 17 + 2.16.0 \ No newline at end of file diff --git a/javafx/README.md b/javafx/README.md index 7db1478129..d6ea5b226f 100644 --- a/javafx/README.md +++ b/javafx/README.md @@ -7,4 +7,4 @@ This module contains articles about JavaFX. - [Introduction to JavaFx](https://www.baeldung.com/javafx) - [Display Custom Items in JavaFX ListView](https://www.baeldung.com/javafx-listview-display-custom-items) - [Adding EventHandler to JavaFX Button](https://www.baeldung.com/javafx-button-eventhandler) - +- [How to Use a Custom Font in Java](https://www.baeldung.com/java-custom-font) diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index a35abb9c19..0db1f46b1e 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -107,8 +107,8 @@ commons-lang3 - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.assertj @@ -1125,7 +1125,6 @@ 3.0.0 - 11 2.12.6 v10.15.0 6.4.1 diff --git a/jhipster-modules/jhipster-microservice/car-app/pom.xml b/jhipster-modules/jhipster-microservice/car-app/pom.xml index f345688939..87c289cb46 100644 --- a/jhipster-modules/jhipster-microservice/car-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/car-app/pom.xml @@ -23,7 +23,7 @@ 0.4.13 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 1.8 3.21.0-GA diff --git a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml index 056bd60f33..f660463026 100644 --- a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml @@ -23,7 +23,7 @@ 0.4.13 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 diff --git a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml index b90f22f009..7c95704da7 100644 --- a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml @@ -26,7 +26,7 @@ 1.3 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 diff --git a/jhipster-modules/jhipster-monolithic/pom.xml b/jhipster-modules/jhipster-monolithic/pom.xml index fbcee8f1ff..bb82c819c4 100644 --- a/jhipster-modules/jhipster-monolithic/pom.xml +++ b/jhipster-modules/jhipster-monolithic/pom.xml @@ -892,7 +892,7 @@ 2.2.1 2.2.3 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 diff --git a/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java b/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java index 8700dc3df4..033281e07f 100644 --- a/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java +++ b/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java @@ -1,52 +1,44 @@ package com.baeldung.configuration; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; @Configuration -public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { +public class WebSecurityConfiguration { - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - + @Bean + public InMemoryUserDetailsManager userDetailsService() { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); - - auth.inMemoryAuthentication() - .withUser("admin").password(encoder.encode("admin")).roles("USER", "ADMIN") - .and() - .withUser("user1").password(encoder.encode("password1")).roles("USER") - .and() - .withUser("user2").password(encoder.encode("password2")).roles("USER") - .and() - .withUser("user3").password(encoder.encode("password3")).roles("USER") - .and() - .withUser("user4").password(encoder.encode("password4")).roles("USER") - .and() - .withUser("user5").password(encoder.encode("password5")).roles("USER") - .and() - .withUser("user6").password(encoder.encode("password6")).roles("USER") - .and() - .withUser("user7").password(encoder.encode("password7")).roles("USER") - .and() - .withUser("user8").password(encoder.encode("password8")).roles("USER") - .and() - .withUser("user9").password(encoder.encode("password9")).roles("USER") - .and() - .withUser("user10").password(encoder.encode("password10")).roles("USER"); + + Set users = new HashSet<>(); + users.add(User.withUsername("admin").password(encoder.encode("admin")).roles("USER", "ADMIN").build()); + for(int i=1;i<=10;i++){ + users.add(User.withUsername("user"+i).password(encoder.encode("password")+i).roles("USER").build()); + } + + return new InMemoryUserDetailsManager(users); } - @Override - protected void configure(HttpSecurity http) throws Exception { - + @Bean + public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { + http .authorizeRequests() .antMatchers("/secured/**").authenticated() .anyRequest().permitAll() .and() .httpBasic(); + + return http.build(); } } diff --git a/json-modules/gson-2/README.md b/json-modules/gson-2/README.md index 3deb61f25d..912f8b0a20 100644 --- a/json-modules/gson-2/README.md +++ b/json-modules/gson-2/README.md @@ -5,4 +5,4 @@ This module contains articles about Gson ### Relevant Articles: - [Solving Gson Parsing Errors](https://www.baeldung.com/gson-parsing-errors) - [Difference between Gson @Expose and @SerializedName](https://www.baeldung.com/gson-expose-vs-serializedname) - +- [Resolving Gson’s “Multiple JSON Fields” Exception](https://www.baeldung.com/java-gson-multiple-json-fields-exception) diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/BasicStudent.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/BasicStudent.java new file mode 100644 index 0000000000..9c8d5f0923 --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/BasicStudent.java @@ -0,0 +1,64 @@ +package com.baeldung.gson.multiplefields; + +import java.util.Objects; + +import com.google.gson.annotations.SerializedName; + +public class BasicStudent { + + private String name; + + private transient String major; + + @SerializedName("major") + private String concentration; + + public BasicStudent() { + + } + + public BasicStudent(String name, String major, String concentration) { + this.name = name; + this.major = major; + this.concentration = concentration; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof BasicStudent)) + return false; + BasicStudent student = (BasicStudent) o; + return Objects.equals(name, student.name) && Objects.equals(major, student.major) && Objects.equals(concentration, student.concentration); + } + + @Override + public int hashCode() { + return Objects.hash(name, major, concentration); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMajor() { + return major; + } + + public void setMajor(String major) { + this.major = major; + } + + public String getConcentration() { + return concentration; + } + + public void setConcentration(String concentration) { + this.concentration = concentration; + } +} diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentExclusionStrategy.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentExclusionStrategy.java new file mode 100644 index 0000000000..5dad30a138 --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentExclusionStrategy.java @@ -0,0 +1,18 @@ +package com.baeldung.gson.multiplefields; + +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; + +public class StudentExclusionStrategy implements ExclusionStrategy { + + @Override + public boolean shouldSkipField(FieldAttributes field) { + // Ignore all field values from V1 type + return field.getDeclaringClass() == StudentV1.class; + } + + @Override + public boolean shouldSkipClass(Class aClass) { + return false; + } +} diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV1.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV1.java new file mode 100644 index 0000000000..49a09b830c --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV1.java @@ -0,0 +1,34 @@ +package com.baeldung.gson.multiplefields; + +public class StudentV1 { + + private String firstName; + private String lastName; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + // Default constructor for Gson + public StudentV1() { + + } + + public StudentV1(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + +} diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV2.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV2.java new file mode 100644 index 0000000000..e31d33e3fd --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV2.java @@ -0,0 +1,71 @@ +package com.baeldung.gson.multiplefields; + +import java.util.Objects; + +import com.google.gson.annotations.Expose; + +public class StudentV2 extends StudentV1 { + + @Expose + private String firstName; + + @Expose + private String lastName; + + @Expose + private String major; + + @Override + public String getFirstName() { + return firstName; + } + + @Override + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + @Override + public String getLastName() { + return lastName; + } + + @Override + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getMajor() { + return major; + } + + public void setMajor(String major) { + this.major = major; + } + + // Default constructor for Gson + public StudentV2() { + + } + + public StudentV2(String firstName, String lastName, String major) { + this.firstName = firstName; + this.lastName = lastName; + this.major = major; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof StudentV2)) + return false; + StudentV2 studentV2 = (StudentV2) o; + return Objects.equals(firstName, studentV2.firstName) && Objects.equals(lastName, studentV2.lastName) && Objects.equals(major, studentV2.major); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName, major); + } +} diff --git a/json-modules/gson-2/src/test/java/com/baeldung/gson/multiplefields/GsonMultipleFieldsUnitTest.java b/json-modules/gson-2/src/test/java/com/baeldung/gson/multiplefields/GsonMultipleFieldsUnitTest.java new file mode 100644 index 0000000000..1ee2cd1bd8 --- /dev/null +++ b/json-modules/gson-2/src/test/java/com/baeldung/gson/multiplefields/GsonMultipleFieldsUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.gson.multiplefields; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class GsonMultipleFieldsUnitTest { + + @Test + public void givenBasicStudent_whenSerializingWithGson_thenTransientFieldNotSet() { + // Given a class with a transient field + BasicStudent student = new BasicStudent("Henry Winter", "Greek Studies", "Classical Greek Studies"); + + // When serializing using Gson + Gson gson = new Gson(); + String json = gson.toJson(student); + + // Then the deserialized instance doesn't contain the transient field value + BasicStudent deserialized = gson.fromJson(json, BasicStudent.class); + assertThat(deserialized.getMajor()).isNull(); + } + + @Test + public void givenStudentV2_whenSerializingWithGson_thenIllegalArgumentExceptionIsThrown() { + // Given a class with a class hierarchy that defines multiple fields with the same name + StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies"); + + // When serializing using Gson, then an IllegalArgumentException exception is thrown + Gson gson = new Gson(); + assertThatThrownBy(() -> gson.toJson(student)).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("declares multiple JSON fields named 'firstName'"); + } + + @Test + public void givenStudentV2_whenSerializingWithGsonExposeAnnotation_thenSerializes() { + // Given a class with a class hierarchy that defines multiple fields with the same name + StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies"); + + // When serializing using Gson exclude fields without @Expose + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() + .create(); + + // Then ensure the student can be serialized, then deserialized back into an equal instance + String json = gson.toJson(student); + assertThat(gson.fromJson(json, StudentV2.class)).isEqualTo(student); + } + + @Test + public void givenStudentV2_whenSerializingWithGsonExclusionStrategy_thenSerializes() { + // Given a class with a class hierarchy that defines multiple fields with the same name + StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies"); + + // When serializing using Gson add an ExclusionStrategy + Gson gson = new GsonBuilder().setExclusionStrategies(new StudentExclusionStrategy()) + .create(); + + // Then ensure the student can be serialized, then deserialized back into an equal instance + assertThat(gson.fromJson(gson.toJson(student), StudentV2.class)).isEqualTo(student); + } + +} \ No newline at end of file diff --git a/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java new file mode 100644 index 0000000000..38d097e5b8 --- /dev/null +++ b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.jsonnodetojsonobject; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class JsonNodeToJsonObjectUnitTest { + + public static String jsonString = "{\"name\": \"John\", \"gender\": \"male\", \"company\": \"Baeldung\", \"isEmployee\": true, \"age\": 30}"; + + @Test + public void givenJsonNode_whenConvertingToObjectNode_thenVerifyFieldsIntegrity() throws JsonProcessingException { + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(jsonString); + ObjectNode objectNode = objectMapper.createObjectNode().setAll((ObjectNode) jsonNode); + + assertEquals("John", objectNode.get("name").asText()); + assertEquals("male", objectNode.get("gender").asText()); + assertEquals("Baeldung", objectNode.get("company").asText()); + assertTrue(objectNode.get("isEmployee").asBoolean()); + assertEquals(30, objectNode.get("age").asInt()); + } +} diff --git a/json-modules/json/README.md b/json-modules/json/README.md index d643914fc7..d6e1b400f5 100644 --- a/json-modules/json/README.md +++ b/json-modules/json/README.md @@ -12,4 +12,5 @@ This module contains articles about JSON. - [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) - [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping) - [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size) +- [How to Convert JsonNode to ObjectNode](https://www.baeldung.com/java-jackson-jsonnode-objectnode) - More Articles: [[next -->]](../json-2) diff --git a/jsoup/pom.xml b/jsoup/pom.xml index 44f8f996f5..d2780424de 100644 --- a/jsoup/pom.xml +++ b/jsoup/pom.xml @@ -22,7 +22,7 @@ - 1.10.2 + 1.16.2 \ No newline at end of file diff --git a/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java index 0958fa96e2..e6bd8eccbf 100644 --- a/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java +++ b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.jsoup; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; -import org.jsoup.safety.Whitelist; +import org.jsoup.safety.Safelist; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -13,7 +13,7 @@ public class PreservingLineBreaksUnitTest { String strHTML = "Hello\nworld"; Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); - String strWithNewLines = Jsoup.clean(strHTML, "", Whitelist.none(), outputSettings); + String strWithNewLines = Jsoup.clean(strHTML, "", Safelist.none(), outputSettings); assertEquals("Hello\nworld", strWithNewLines); } @@ -33,7 +33,7 @@ public class PreservingLineBreaksUnitTest { jsoupDoc.select("p").before("\\n"); String str = jsoupDoc.html().replaceAll("\\\\n", "\n"); String strWithNewLines = - Jsoup.clean(str, "", Whitelist.none(), outputSettings); + Jsoup.clean(str, "", Safelist.none(), outputSettings); assertEquals("Hello\nWorld\nParagraph", strWithNewLines); } } diff --git a/ksqldb/pom.xml b/ksqldb/pom.xml index e55398d635..ebb3bfa7ee 100644 --- a/ksqldb/pom.xml +++ b/ksqldb/pom.xml @@ -17,7 +17,7 @@ confluent confluent-repo - http://packages.confluent.io/maven/ + https://packages.confluent.io/maven/ diff --git a/kubernetes-modules/k8s-admission-controller/pom.xml b/kubernetes-modules/k8s-admission-controller/pom.xml index 18bf98a830..4c41bf7ca0 100644 --- a/kubernetes-modules/k8s-admission-controller/pom.xml +++ b/kubernetes-modules/k8s-admission-controller/pom.xml @@ -22,6 +22,7 @@ org.projectlombok lombok + ${lombok.version} true diff --git a/kubernetes-modules/kubernetes-spring/pom.xml b/kubernetes-modules/kubernetes-spring/pom.xml index 05532ab0b0..64322055d1 100644 --- a/kubernetes-modules/kubernetes-spring/pom.xml +++ b/kubernetes-modules/kubernetes-spring/pom.xml @@ -46,8 +46,4 @@ - - 11 - - \ No newline at end of file diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index 9fa44d3a32..f073ca424c 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -197,7 +197,7 @@ 1.10.0 2.7.1 4.8.1 - 0.12.1 + 2.1.0 1.15 3.6 3.5-beta72 diff --git a/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java b/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java index 1d69d20bc2..ab4d9dde40 100644 --- a/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java +++ b/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java @@ -43,7 +43,7 @@ public class Resilience4jUnitTest { // Percentage of failures to start short-circuit .failureRateThreshold(20) // Min number of call attempts - .ringBufferSizeInClosedState(5) + .slidingWindowSize(5) .build(); CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config); CircuitBreaker circuitBreaker = registry.circuitBreaker("my"); @@ -70,7 +70,7 @@ public class Resilience4jUnitTest { Future taskInProgress = callAndBlock(decorated); try { - assertThat(bulkhead.isCallPermitted()).isFalse(); + assertThat(bulkhead.tryAcquirePermission()).isFalse(); } finally { taskInProgress.cancel(true); } diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index ed184d72e0..6ee8daa2a5 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -152,6 +152,7 @@ org.projectlombok lombok + ${lombok.version} io.ebean @@ -299,7 +300,7 @@ 6.0.0-release 6.0.1 3.2.1 - 5.0.1 + 5.1.0 13.15.2 2.1.3.Final 2.2.3 diff --git a/libraries-data-io/pom.xml b/libraries-data-io/pom.xml index c8d895b4e5..9fc2814312 100644 --- a/libraries-data-io/pom.xml +++ b/libraries-data-io/pom.xml @@ -98,7 +98,7 @@ - 1.21 + 2.2 4.0.1 1.7.0 5.8 diff --git a/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java b/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java index cee73f674e..e18277b328 100644 --- a/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java +++ b/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java @@ -14,52 +14,52 @@ import java.util.List; public class Application { // CSV Reader Examples - public static List readLineByLineSyncExample() throws Exception { + public static List readLineByLineExample() throws Exception { Path path = Helpers.twoColumnCsvPath(); return CsvReaderExamples.readLineByLine(path); } - public static List readAllLinesSyncExample() throws Exception { + public static List readAllLinesExample() throws Exception { Path path = Helpers.twoColumnCsvPath(); return CsvReaderExamples.readAllLines(path); } // CSV Writer Examples - public static String writeLineByLineSyncExample() throws Exception { + public static String writeLineByLineExample() throws Exception { Path path = Helpers.fileOutOnePath(); return CsvWriterExamples.writeLineByLine(Helpers.fourColumnCsvString(), path); } - public static String writeAllLinesSyncExample() throws Exception { + public static String writeAllLinesExample() throws Exception { Path path = Helpers.fileOutAllPath(); return CsvWriterExamples.writeAllLines(Helpers.fourColumnCsvString(), path); } // Bean Examples - public static List simpleSyncPositionBeanExample() throws Exception { + public static List simplePositionBeanExample() throws Exception { Path path = Helpers.twoColumnCsvPath(); return BeanExamples.beanBuilderExample(path, SimplePositionBean.class); } - public static List namedSyncColumnBeanExample() throws Exception { + public static List namedColumnBeanExample() throws Exception { Path path = Helpers.namedColumnCsvPath(); return BeanExamples.beanBuilderExample(path, NamedColumnBean.class); } - public static String writeSyncCsvFromBeanExample() throws Exception { + public static String writeCsvFromBeanExample() throws Exception { Path path = Helpers.fileOutBeanPath(); return BeanExamples.writeCsvFromBean(path); } public static void main(String[] args) { try { - simpleSyncPositionBeanExample(); - namedSyncColumnBeanExample(); - writeSyncCsvFromBeanExample(); - readLineByLineSyncExample(); - readAllLinesSyncExample(); - writeLineByLineSyncExample(); - writeAllLinesSyncExample(); + simplePositionBeanExample(); + namedColumnBeanExample(); + writeCsvFromBeanExample(); + readLineByLineExample(); + readAllLinesExample(); + writeLineByLineExample(); + writeAllLinesExample(); } catch (Exception e) { throw new RuntimeException("Error during csv processing", e); } diff --git a/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java b/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java index 6745b9be7f..c3c85c5baa 100644 --- a/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java +++ b/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java @@ -13,7 +13,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadUsingPosition_thenContentsRead() throws Exception { - List values = Application.simpleSyncPositionBeanExample(); + List values = Application.simplePositionBeanExample(); assertThat(values) .extracting(Object::toString) @@ -28,7 +28,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadUsingNamedColumn_thenContentsRead() throws Exception { - List values = Application.namedSyncColumnBeanExample(); + List values = Application.namedColumnBeanExample(); assertThat(values) .extracting(Object::toString) @@ -41,7 +41,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadLineByLine_thenContentsRead() throws Exception { - List lineByLineContents = Application.readLineByLineSyncExample(); + List lineByLineContents = Application.readLineByLineExample(); assertThat(lineByLineContents) .containsExactly( @@ -56,7 +56,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadAllLines_thenContentsRead() throws Exception { - List contents = Application.readAllLinesSyncExample(); + List contents = Application.readAllLinesExample(); assertThat(contents) .containsExactly( @@ -70,7 +70,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenWriteCsvUsingBean_thenContentsWritten() throws Exception { - String contents = Application.writeSyncCsvFromBeanExample(); + String contents = Application.writeCsvFromBeanExample(); assertThat(contents.split(NEW_LINE)) .containsExactly( @@ -82,7 +82,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenWriteCsvLineByLine_thenContentsWritten() throws Exception { - String contents = Application.writeLineByLineSyncExample(); + String contents = Application.writeLineByLineExample(); assertThat(contents.split(NEW_LINE)) .containsExactly( @@ -94,7 +94,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenWriteCsvAllLines_thenContentsWritten() throws Exception { - String contents = Application.writeAllLinesSyncExample(); + String contents = Application.writeAllLinesExample(); assertThat(contents.split(NEW_LINE)) .containsExactly( diff --git a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java index 6f32f143a9..4c92bf41e1 100644 --- a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java +++ b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java @@ -1,15 +1,19 @@ package com.baeldung.libraries.snakeyaml; -import org.junit.Test; -import org.yaml.snakeyaml.TypeDescription; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Date; import java.util.Map; -import static org.junit.Assert.*; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.inspector.TagInspector; public class YAMLToJavaDeserialisationUnitTest { @@ -27,7 +31,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObject() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class,new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer.yaml"); @@ -39,7 +43,11 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithAssumedClass_thenLoadCorrectJavaObject() { - Yaml yaml = new Yaml(); + LoaderOptions loaderoptions = new LoaderOptions(); + TagInspector taginspector = tag -> tag.getClassName() + .equals(Customer.class.getName()); + loaderoptions.setTagInspector(taginspector); + Yaml yaml = new Yaml(new Constructor(Customer.class, loaderoptions)); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer_with_type.yaml"); @@ -61,7 +69,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class, new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer_with_contact_details_and_address.yaml"); @@ -91,7 +99,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() { - Constructor constructor = new Constructor(Customer.class); + Constructor constructor = new Constructor(Customer.class, new LoaderOptions()); TypeDescription customTypeDescription = new TypeDescription(Customer.class); customTypeDescription.addPropertyParameters("contactDetails", Contact.class); constructor.addTypeDescription(customTypeDescription); @@ -116,7 +124,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class, new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customers.yaml"); diff --git a/lightrun/lightrun-api-service/pom.xml b/lightrun/lightrun-api-service/pom.xml index b7ed5f951b..77dbbb8b99 100644 --- a/lightrun/lightrun-api-service/pom.xml +++ b/lightrun/lightrun-api-service/pom.xml @@ -40,8 +40,4 @@ - - 17 - - \ No newline at end of file diff --git a/lightrun/lightrun-tasks-service/pom.xml b/lightrun/lightrun-tasks-service/pom.xml index 2689a9794d..773c81a9d5 100644 --- a/lightrun/lightrun-tasks-service/pom.xml +++ b/lightrun/lightrun-tasks-service/pom.xml @@ -65,8 +65,4 @@ - - 17 - - \ No newline at end of file diff --git a/lightrun/lightrun-users-service/pom.xml b/lightrun/lightrun-users-service/pom.xml index 40594db725..0b3e856069 100644 --- a/lightrun/lightrun-users-service/pom.xml +++ b/lightrun/lightrun-users-service/pom.xml @@ -57,8 +57,4 @@ - - 17 - - \ No newline at end of file diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index 8df95c18bb..fbd180c74d 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -121,7 +121,6 @@ 2.0.0 1.4.8 2.0.4 - 1.18.22 \ No newline at end of file diff --git a/maven-modules/dependency-exclusion/pom.xml b/maven-modules/dependency-exclusion/pom.xml index 6e348377b0..6a491e552f 100644 --- a/maven-modules/dependency-exclusion/pom.xml +++ b/maven-modules/dependency-exclusion/pom.xml @@ -62,7 +62,7 @@ junit junit - 4.13 + ${junit.version} diff --git a/maven-modules/maven-exec-plugin/pom.xml b/maven-modules/maven-exec-plugin/pom.xml index 1bac52ae2c..370b344167 100644 --- a/maven-modules/maven-exec-plugin/pom.xml +++ b/maven-modules/maven-exec-plugin/pom.xml @@ -47,7 +47,6 @@ 1.2.6 3.11.0 3.1.0 - 1.8 \ No newline at end of file diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml index 7de3f15298..d73ffe8b1d 100644 --- a/maven-modules/maven-generate-war/pom.xml +++ b/maven-modules/maven-generate-war/pom.xml @@ -70,10 +70,7 @@ - 11 2.17.1 - 11 - 11 \ No newline at end of file diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml index 27524637ab..f96d57b960 100644 --- a/messaging-modules/pom.xml +++ b/messaging-modules/pom.xml @@ -20,8 +20,8 @@ jgroups rabbitmq spring-amqp - spring-apache-camel - spring-jms + + postgres-notify diff --git a/messaging-modules/postgres-notify/pom.xml b/messaging-modules/postgres-notify/pom.xml index 876519f40c..a9b930543b 100644 --- a/messaging-modules/postgres-notify/pom.xml +++ b/messaging-modules/postgres-notify/pom.xml @@ -41,13 +41,11 @@ org.projectlombok lombok true + ${lombok.version} - - 1.8 - diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java index 70daa14abd..4a1db320dc 100644 --- a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java @@ -42,7 +42,7 @@ public class OrdersController { public ResponseEntity getOrderById(@PathVariable Long id) { Optional o = orders.findById(id); - if (o.isEmpty()) { + if (!o.isPresent()) { return ResponseEntity.notFound().build(); } diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java index 61b970f3a2..da333b89ff 100644 --- a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java @@ -23,7 +23,7 @@ public class NotificationHandler implements Consumer{ public void accept(PGNotification t) { log.info("Notification received: pid={}, name={}, param={}",t.getPID(),t.getName(),t.getParameter()); Optional order = orders.findById(Long.valueOf(t.getParameter())); - if ( !order.isEmpty()) { + if ( order.isPresent()) { log.info("order details: {}", order.get()); } } diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java index cc369c1f3e..038c2f6492 100644 --- a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java @@ -43,14 +43,14 @@ public class OrdersService { @Transactional(readOnly = true) public Optional findById(Long id) { Optional o = Optional.ofNullable(ordersCache.get(id, Order.class)); - if ( !o.isEmpty() ) { + if ( o.isPresent() ) { log.info("findById: cache hit, id={}",id); return o; } log.info("findById: cache miss, id={}",id); o = repo.findById(id); - if ( o.isEmpty()) { + if ( !o.isPresent()) { return o; } diff --git a/microservices-modules/rest-express/pom.xml b/microservices-modules/rest-express/pom.xml index 182d14cfbf..1b22bb8117 100644 --- a/microservices-modules/rest-express/pom.xml +++ b/microservices-modules/rest-express/pom.xml @@ -73,7 +73,7 @@ junit junit - ${junit4.version} + ${junit.version} jar test true @@ -143,7 +143,6 @@ 0.11.3 1.0 0.4.8 - 4.11 2.4.1 2.0 diff --git a/netflix-modules/mantis/pom.xml b/netflix-modules/mantis/pom.xml index 351f079481..ed57eed01e 100644 --- a/netflix-modules/mantis/pom.xml +++ b/netflix-modules/mantis/pom.xml @@ -43,6 +43,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index b79be81a66..9b40dbbe8e 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -25,8 +25,8 @@ import - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -106,7 +106,7 @@ 1.0.22.RELEASE 2.7.11 1.9.20.1 - 8.0.31 + 8.2.0 \ No newline at end of file diff --git a/parent-boot-3/pom.xml b/parent-boot-3/pom.xml index 9f9d6f7901..f1ab699c83 100644 --- a/parent-boot-3/pom.xml +++ b/parent-boot-3/pom.xml @@ -233,9 +233,6 @@ 3.1.5 5.8.2 0.9.17 - 17 - ${java.version} - ${java.version} 1.4.4 2.0.3 diff --git a/patterns-modules/design-patterns-architectural/pom.xml b/patterns-modules/design-patterns-architectural/pom.xml index 4efcca0c6b..20f320f073 100644 --- a/patterns-modules/design-patterns-architectural/pom.xml +++ b/patterns-modules/design-patterns-architectural/pom.xml @@ -36,8 +36,8 @@ ${hibernate-core.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector.version} jar @@ -65,7 +65,7 @@ 5.2.16.Final - 6.0.6 + 8.2.0 2.7.5 5.3.0 2.7.5 diff --git a/pdf/pom.xml b/pdf/pom.xml index 0fe90b6eb5..041f356b9a 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -111,12 +111,12 @@ 3.15 1.8 3.15 - 3.0.11.RELEASE - 9.1.20 + 3.1.2.RELEASE + 9.3.1 1.0.6 - 1.0.6 - 9.1.22 - 1.14.2 + 1.0.10 + 9.2.1 + 1.16.2 \ No newline at end of file diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index d22a9cf3ac..7927c518f9 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -164,7 +164,7 @@ 3.2.4 3.0.0-M1 3.2.0 - 3.2.0 + 3.6.2 3.1.0 3.9.1 3.2.1 diff --git a/persistence-modules/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml index a661fc3abb..e41af5c64b 100644 --- a/persistence-modules/activejdbc/pom.xml +++ b/persistence-modules/activejdbc/pom.xml @@ -28,8 +28,8 @@ - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.version} @@ -64,8 +64,8 @@ - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.version} @@ -76,7 +76,7 @@ 3.4-j11 development.test,development - 8.0.32 + 8.2.0 \ No newline at end of file diff --git a/persistence-modules/apache-cayenne/pom.xml b/persistence-modules/apache-cayenne/pom.xml index 87bf6fe30b..3715198d84 100644 --- a/persistence-modules/apache-cayenne/pom.xml +++ b/persistence-modules/apache-cayenne/pom.xml @@ -22,8 +22,8 @@ ${cayenne.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.version} runtime @@ -40,7 +40,7 @@ - 5.1.44 + 8.2.0 4.0.M5 diff --git a/atomikos/README.md b/persistence-modules/atomikos/README.md similarity index 100% rename from atomikos/README.md rename to persistence-modules/atomikos/README.md diff --git a/atomikos/pom.xml b/persistence-modules/atomikos/pom.xml similarity index 98% rename from atomikos/pom.xml rename to persistence-modules/atomikos/pom.xml index 2cbc106268..c1748f7dac 100644 --- a/atomikos/pom.xml +++ b/persistence-modules/atomikos/pom.xml @@ -8,7 +8,7 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT diff --git a/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java diff --git a/atomikos/src/main/resources/logback.xml b/persistence-modules/atomikos/src/main/resources/logback.xml similarity index 100% rename from atomikos/src/main/resources/logback.xml rename to persistence-modules/atomikos/src/main/resources/logback.xml diff --git a/atomikos/src/main/resources/schema.sql b/persistence-modules/atomikos/src/main/resources/schema.sql similarity index 100% rename from atomikos/src/main/resources/schema.sql rename to persistence-modules/atomikos/src/main/resources/schema.sql diff --git a/atomikos/src/main/resources/transactions.properties b/persistence-modules/atomikos/src/main/resources/transactions.properties similarity index 100% rename from atomikos/src/main/resources/transactions.properties rename to persistence-modules/atomikos/src/main/resources/transactions.properties diff --git a/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java b/persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java similarity index 100% rename from atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java rename to persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java b/persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java similarity index 100% rename from atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java rename to persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java b/persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java similarity index 100% rename from atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java rename to persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java diff --git a/atomikos/src/test/resources/logback.xml b/persistence-modules/atomikos/src/test/resources/logback.xml similarity index 100% rename from atomikos/src/test/resources/logback.xml rename to persistence-modules/atomikos/src/test/resources/logback.xml diff --git a/atomikos/src/test/resources/transactions.properties b/persistence-modules/atomikos/src/test/resources/transactions.properties similarity index 100% rename from atomikos/src/test/resources/transactions.properties rename to persistence-modules/atomikos/src/test/resources/transactions.properties diff --git a/persistence-modules/core-java-persistence-2/pom.xml b/persistence-modules/core-java-persistence-2/pom.xml index 2013bdb6af..dea261adca 100644 --- a/persistence-modules/core-java-persistence-2/pom.xml +++ b/persistence-modules/core-java-persistence-2/pom.xml @@ -28,8 +28,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.driver.version} @@ -85,7 +85,7 @@ 8.4.1.jre11 10.2.0.4.0 - 8.0.22 + 8.2.0 3.11.11 20220320 07.00.00-MS-GA diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index e8add07fbf..20553da4e8 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -53,8 +53,8 @@ ${springframework.boot.spring-boot-starter.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector.version} runtime @@ -62,11 +62,11 @@ 2.9.0 - 5.0.1 + 5.1.0 0.9.5.5 3.0.4 6.0.6 - 8.0.32 + 8.2.0 \ No newline at end of file diff --git a/persistence-modules/fauna/pom.xml b/persistence-modules/fauna/pom.xml index a0626e0cd2..4c37c2ae9e 100644 --- a/persistence-modules/fauna/pom.xml +++ b/persistence-modules/fauna/pom.xml @@ -44,6 +44,7 @@ org.projectlombok lombok provided + ${lombok.version} @@ -57,7 +58,6 @@ - 17 4.2.0 diff --git a/persistence-modules/flyway/pom.xml b/persistence-modules/flyway/pom.xml index 18ff9fdb39..df35f85bfb 100644 --- a/persistence-modules/flyway/pom.xml +++ b/persistence-modules/flyway/pom.xml @@ -25,8 +25,8 @@ spring-boot-starter-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml index 954f8f40d3..caf7b37a41 100644 --- a/persistence-modules/hibernate-enterprise/pom.xml +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -35,8 +35,8 @@ ${geodb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -79,7 +79,7 @@ 6.1.7.Final - 8.0.32 + 8.2.0 2.6.0 0.9 diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml index 5a99c1c4d0..603c749e95 100644 --- a/persistence-modules/hibernate-jpa/pom.xml +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -56,8 +56,8 @@ ${hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -83,7 +83,7 @@ - 8.0.32 + 8.2.0 2.6.0 3.0.4 2.1.214 diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index 3f4da28296..3fa15ffb0b 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -63,8 +63,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} runtime @@ -162,13 +162,13 @@ 1.6 2.9.7 - 5.4.14.Final + 5.6.15.Final 3.27.0-GA 2.3.1 2.0.0 3.8.1 3.8.1 - 8.0.19 + 8.2.0 2.1.3.RELEASE diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 0ce112b9e6..45d8e24b41 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -86,7 +86,7 @@ 3.0.1-b11 1.1 1.4.2 - 2.14.2 + 2.16.0 \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index 76f230a72d..0a736346a4 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -60,8 +60,8 @@ ${hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -96,7 +96,7 @@ 6.0.6 3.0.3 9.0.0.M26 - 8.0.32 + 8.2.0 2.6.0 2.1.214 6.3.1.Final diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 1a2c65c6ba..f93fe6c9e7 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -30,8 +30,8 @@ ${hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -58,7 +58,7 @@ 5.4.24.Final - 6.0.6 + 8.2.0 2.2.3 2.1.214 diff --git a/persistence-modules/java-harperdb/README.md b/persistence-modules/java-harperdb/README.md new file mode 100644 index 0000000000..99a91e00ed --- /dev/null +++ b/persistence-modules/java-harperdb/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Working With HarperDB and Java](https://www.baeldung.com/java-harperdb) diff --git a/persistence-modules/java-harperdb/pom.xml b/persistence-modules/java-harperdb/pom.xml new file mode 100644 index 0000000000..318f4b7460 --- /dev/null +++ b/persistence-modules/java-harperdb/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + + com.baeldung + java-harperdb + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + + + + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + com.baeldung + java-harperdb + ${haperdb-driver.version} + system + ${project.basedir}/lib/cdata.jdbc.harperdb.jar + + + org.testcontainers + testcontainers + test + + + org.apache.derby + derby + 10.13.1.1 + + + + + + + org.testcontainers + testcontainers-bom + 1.19.3 + pom + import + + + + + + 4.2 + + + \ No newline at end of file diff --git a/persistence-modules/java-harperdb/src/main/resources/data-model.puml b/persistence-modules/java-harperdb/src/main/resources/data-model.puml new file mode 100644 index 0000000000..8e3681c749 --- /dev/null +++ b/persistence-modules/java-harperdb/src/main/resources/data-model.puml @@ -0,0 +1,41 @@ +@startuml +'https://gist.github.com/QuantumGhost/0955a45383a0b6c0bc24f9654b3cb561 +' uncomment the line below if you're using computer with a retina display +' skinparam dpi 300 +!theme sketchy-outline +!define Table(name,desc) class name as "desc" << (T, #63b175) >> +' we use bold for primary key +' green color for unique +' and underscore for not_null +!define primary_key(x) x +!define unique(x) x +!define not_null(x) x +' other tags available: +' +' , where color is a color name or html color code +' (#FFAACC) +' see: http://plantuml.com/classes.html#More +hide methods +hide stereotypes + +' entities + + +Table(Teacher, "Teacher") { + primary_key(Id) Number + Name Varchar + joining_date Date +} +Table(Subject, "Subject") { + primary_key(Id) Number + Name Varchar +} +Table(Teacher_Details, "Teacher_Details") { + primary_key(Id) Number + teacher_id Number + subject_id Number +} + +Teacher_Details "*" -left-> "1" Subject: " " +Teacher "1" -left-> "*" Teacher_Details: " " +@enduml \ No newline at end of file diff --git a/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBApiService.java b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBApiService.java new file mode 100644 index 0000000000..361e17bd83 --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBApiService.java @@ -0,0 +1,78 @@ +package com.baeldung.harperdb; + +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.classic.methods.HttpPost; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.ClassicHttpRequest; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.HttpEntity; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.io.entity.StringEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.Base64; + +public class HarperDBApiService { + private static final Logger LOGGER = LoggerFactory.getLogger(HarperDBApiService.class); + private String url; + private String base64auth; + + public HarperDBApiService(String url, String user, String password) { + this.url = url; + this.base64auth = Base64.getEncoder() + .encodeToString(new StringBuilder().append(user) + .append(":") + .append(password) + .toString() + .getBytes()); + } + + public void createSchema(String schema) throws IOException { + String requestBody = "{\"operation\":\"create_schema\", \"" + "schema\":\"" + schema + "\"" + "}"; + executeHttpPostRequest(requestBody); + } + + public void createTable(String schema, String table, String ... attributes) throws IOException { + String createTableReq = "{\"operation\":\"create_table\"," + + "\"schema\":\"" + schema + + "\",\"table\":\"" + table + + "\",\"hash_attribute\":\"id\"" + + "}"; + executeHttpPostRequest(createTableReq); + LOGGER.info("created table:" + table); + for (String attribute : attributes) { + String createAttrReq = "{\"operation\":\"create_attribute\",\"schema\":\"" + + schema + "\",\"table\":\"" + + table + "\",\"attribute\":\"" + + attribute + "\"" + + "}"; + executeHttpPostRequest(createAttrReq); + LOGGER.info("created attribute:" + attribute + " in table:" + table); + } + } + + public void insertRecords(String schema, String table, String records) throws IOException { + String requestBody = "{\"table\":" + "\"" + table + "\"," + + "\"schema\":" + "\"" + schema + "\"" + "," + + "\"operation\":" + "\"" + "insert" + "\"" + "," + + "\"records\":" + records + + "}"; + executeHttpPostRequest(requestBody); + } + + private void executeHttpPostRequest(String httpRequest) throws IOException { + LOGGER.info("Post request body:" + httpRequest); + + try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create() + .build()) { + HttpPost request = new HttpPost(this.url); + request.addHeader("Authorization", "Basic " + this.base64auth); + request.addHeader("Content-Type", "application/json"); + request.setEntity((HttpEntity) new StringEntity(httpRequest)); + CloseableHttpResponse response = closeableHttpClient.execute((ClassicHttpRequest) request); + LOGGER.info("REST API response:" + response.toString()); + assert (200 == response.getCode()); + } + } +} diff --git a/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBContainer.java b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBContainer.java new file mode 100644 index 0000000000..12ef87fa99 --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBContainer.java @@ -0,0 +1,36 @@ +package com.baeldung.harperdb; + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.GenericContainer; + +public class HarperDBContainer { + + private final static Logger LOGGER = LoggerFactory.getLogger(HarperDBContainer.class); + + private static final Map DEFAULT_ENV_MAP = Map.of("HDB_ADMIN_USERNAME", "admin", "HDB_ADMIN_PASSWORD", "password", + "OPERATIONSAPI_NETWORK_PORT", "9925", "ROOTPATH", "/home/harperdb/hdb", "LOGGING_STDSTREAMS", "true"); + + private static final Integer[] DEFAULT_EXPOSED_PORTS = { 9925, 9926 }; + + private static final String HARPER_DOCKER_IMAGE = "harperdb/harperdb:latest"; + + public void stop() { + harperDBContainer.stop(); + } + + GenericContainer harperDBContainer; + + public GenericContainer installHarperDB() { + harperDBContainer = new GenericContainer(HARPER_DOCKER_IMAGE).withEnv(DEFAULT_ENV_MAP) + .withExposedPorts(DEFAULT_EXPOSED_PORTS); + return harperDBContainer; + } + + public GenericContainer installHarperDB(String dockerImgage, final Map envMap, final Integer... exposedPorts) { + return new GenericContainer(dockerImgage).withEnv(envMap) + .withExposedPorts(exposedPorts); + } +} diff --git a/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBLiveTest.java b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBLiveTest.java new file mode 100644 index 0000000000..34d2f8d29b --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBLiveTest.java @@ -0,0 +1,379 @@ +package com.baeldung.harperdb; + +import cdata.jdbc.harperdb.HarperDBConnectionPoolDataSource; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.GenericContainer; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.sql.*; +import java.util.Arrays; +import java.util.Map; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.*; + +public class HarperDBLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(HarperDBLiveTest.class); + + private static Integer port; + + private static HarperDBContainer harperDBContainer; + + private static HarperDBApiService harperDbApiService; + + @BeforeAll + static void setupHarperDB() throws IOException, InterruptedException, URISyntaxException { + installHarperDB(); + initHarperDBApiService(); + setupDB(); + } + + private static void installHarperDB() { + harperDBContainer = new HarperDBContainer(); + + GenericContainer genericContainer = harperDBContainer.installHarperDB(); + + genericContainer.start(); + + port = genericContainer.getFirstMappedPort(); + } + + private static void initHarperDBApiService() { + String url = "http://localhost:" + port + "/"; + harperDbApiService = new HarperDBApiService(url, "admin", "password"); + } + + private static void setupDB() throws IOException { + harperDbApiService.createSchema("Demo"); + + harperDbApiService.createTable("Demo", "Subject", "name"); + harperDbApiService.createTable("Demo", "Teacher", "name", "joining_date", "subject_id"); + harperDbApiService.createTable("Demo", "Teacher_Details", "teacher_id", "subject_id"); + + insertSubjectRecords(); + insertTeacherRecords(); + insertTeacherDetailsRecords(); + } + + private static void insertSubjectRecords() throws IOException { + String records = "[" + + "{\"id\":1, \"name\":\"English\"}," + + "{\"id\":2, \"name\":\"Maths\"}," + + "{\"id\":3, \"name\":\"Science\"}" + + "]"; + + harperDbApiService.insertRecords("Demo", "Subject", records); + } + + private static void insertTeacherRecords() throws IOException { + String records = "[" + "{\"id\":1, \"name\":\"James Cameron\", \"joining_date\":\"04-05-2000\"}," + + "{\"id\":2, \"name\":\"Joe Biden\", \"joining_date\":\"20-10-2005\"}," + + "{\"id\":3, \"name\":\"Jessie Williams\", \"joining_date\":\"04-06-1997\"}," + + "{\"id\":4, \"name\":\"Robin Williams\", \"joining_date\":\"01-01-2020\"}," + + "{\"id\":5, \"name\":\"Eric Johnson\", \"joining_date\":\"04-05-2022\"}," + + "{\"id\":6, \"name\":\"Raghu Yadav\", \"joining_date\":\"02-02-1999\"}" + "]"; + harperDbApiService.insertRecords("Demo", "Teacher", records); + } + + private static void insertTeacherDetailsRecords() throws IOException { + String records = "[" + "{\"id\":1, \"teacher_id\":1, \"subject_id\":1}," + "{\"id\":2, \"teacher_id\":1, \"subject_id\":2}," + + "{\"id\":3, \"teacher_id\":2, \"subject_id\":3 }," + "{\"id\":4, \"teacher_id\":3, \"subject_id\":1}," + + "{\"id\":5, \"teacher_id\":3, \"subject_id\":3}," + "{\"id\":6, \"teacher_id\":4, \"subject_id\":2}," + + "{\"id\":7, \"teacher_id\":5, \"subject_id\":3}," + "{\"id\":8, \"teacher_id\":6, \"subject_id\":1}," + + "{\"id\":9, \"teacher_id\":6, \"subject_id\":2}," + "{\"id\":15, \"teacher_id\":6, \"subject_id\":3}" + "]"; + + harperDbApiService.insertRecords("Demo", "Teacher_Details", records); + } + + @AfterAll + static void stopHarperDB() { + harperDBContainer.stop(); + } + + @Test + void whenConnectionInfoInURL_thenConnectSuccess() { + assertDoesNotThrow(() -> { + final String JDBC_URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + + try (Connection connection = DriverManager.getConnection(JDBC_URL)) { + connection.createStatement() + .executeQuery("select 1"); + logger.info("Connection Successful"); + } + }); + } + + @Test + void whenConnectionInfoInProperties_thenConnectSuccess() { + assertDoesNotThrow(() -> { + Properties prop = new Properties(); + prop.setProperty("Server", "127.0.0.1:" + port); + prop.setProperty("User", "admin"); + prop.setProperty("Password", "password"); + + try (Connection connection = DriverManager.getConnection("jdbc:harperdb:", prop)) { + connection.createStatement() + .executeQuery("select 1"); + logger.info("Connection Successful"); + } + }); + } + + @Test + void whenConnectionPooling_thenConnectSuccess() { + assertDoesNotThrow(() -> { + HarperDBConnectionPoolDataSource harperdbPoolDataSource = new HarperDBConnectionPoolDataSource(); + final String JDBC_URL = "jdbc:harperdb:UseConnectionPooling=true;PoolMaxSize=2;Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + harperdbPoolDataSource.setURL(JDBC_URL); + + try (Connection connection = harperdbPoolDataSource.getPooledConnection() + .getConnection()) { + connection.createStatement() + .executeQuery("select 1"); + logger.info("Connection Pool Successful"); + } + }); + } + + @Test + void whenExecuteStoredToCreateTable_thenSuccess() throws SQLException { + final String CREATE_TABLE_PROC = "CreateTable"; + try (Connection connection = getConnection()) { + CallableStatement callableStatement = connection.prepareCall(CREATE_TABLE_PROC); + + callableStatement.setString("SchemaName", "prod"); + callableStatement.setString("TableName", "subject"); + callableStatement.setString("PrimaryKey", "id"); + Boolean result = callableStatement.execute(); + + ResultSet resultSet = callableStatement.getResultSet(); + + while (resultSet.next()) { + String tableCreated = resultSet.getString("Success"); + assertEquals("true", tableCreated); + logger.info("Table Created Successfully"); + } + } + } + + @Test + void givenStatement_whenInsertRecord_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into Demo.Subject(id, name) values " + + "(4, 'Social Studies')," + + "(5, 'Geography')"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); + assertEquals(2, statement.getUpdateCount()); + } + } + + @Test + void givenPrepareStatement_whenAddToBatch_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into Demo.Teacher(id, name, joining_date) values" + + "(?, ?, ?)"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(INSERT_SQL); + preparedStatement.setInt(1, 7); + preparedStatement.setString(2, "Bret Lee"); + preparedStatement.setString(3, "07-08-2002"); + preparedStatement.addBatch(); + + preparedStatement.setInt(1, 8); + preparedStatement.setString(2, "Sarah Glimmer"); + preparedStatement.setString(3, "07-08-1997"); + preparedStatement.addBatch(); + + int[] recordsInserted = preparedStatement.executeBatch(); + + assertEquals(2, Arrays.stream(recordsInserted).sum()); + } + } + + private static Connection getConnection() throws SQLException { + String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + return DriverManager.getConnection(URL); + } + + private static Connection getConnection(Map properties) throws SQLException { + Properties prop = new Properties(); + prop.setProperty("Server", "127.0.0.1:" + port); + prop.setProperty("User", "admin"); + prop.setProperty("Password", "password"); + for (Map.Entry entry : properties.entrySet()) { + prop.setProperty(entry.getKey(), entry.getValue()); + } + + return DriverManager.getConnection("jdbc:harperdb:", prop); + } + + @Test + void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { + final String SQL_QUERY = "select id, name from Demo.Subject where name = 'Maths'"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(SQL_QUERY); + while (resultSet.next()) { + Integer id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + assertNotNull(id); + assertEquals("Maths", name); + logger.info("Subject id:" + id + " Subject Name:" + name); + } + } + } + + @Test + void givenPreparedStatement_whenExecuteJoinQuery_thenSuccess() throws SQLException { + final String JOIN_QUERY = "SELECT t.name as teacher_name, t.joining_date as joining_date, s.name as subject_name " + + "from Demo.Teacher_Details AS td " + + "INNER JOIN Demo.Teacher AS t ON t.id = td.teacher_id " + + "INNER JOIN Demo.Subject AS s on s.id = td.subject_id " + + "where t.name = ?"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(JOIN_QUERY); + preparedStatement.setString(1, "Eric Johnson"); + + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + String teacherName = resultSet.getString("teacher_name"); + String subjectName = resultSet.getString("subject_name"); + String joiningDate = resultSet.getString("joining_date"); + assertEquals("Eric Johnson", teacherName); + assertEquals("Maths", subjectName); + logger.info("Teacher Name:" + teacherName + " Subject Name:" + subjectName + " Joining Date:" + joiningDate); + } + } + } + + @Test + void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update Demo.Teacher_Details set subject_id = 2 " + + "where teacher_id in (2, 5)"; + final String UPDATE_SQL_WITH_SUB_QUERY = "update Demo.Teacher_Details " + + "set subject_id = (select id from Demo.Subject where name = 'Maths') " + + "where teacher_id in (select id from Demo.Teacher where name in ('Joe Biden', 'Eric Johnson'))"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(UPDATE_SQL)); + assertEquals(2, statement.getUpdateCount()); + } + + try (Connection connection = getConnection()) { + assertThrows(SQLException.class, () -> connection.createStatement().execute(UPDATE_SQL_WITH_SUB_QUERY)); + } + } + + @Test + void givenPreparedStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update Demo.Teacher_Details set subject_id = ? " + + "where teacher_id in (?, ?)"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SQL); + preparedStatement.setInt(1, 1); + //following is not supported by the HarperDB driver + //Integer[] teacherIds = {4, 5}; + //Array teacherIdArray = connection.createArrayOf(Integer.class.getTypeName(), teacherIds); + preparedStatement.setInt(2, 4); + preparedStatement.setInt(3, 5); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(2, preparedStatement.getUpdateCount()); + } + } + + @Test + void givenStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from Demo.Teacher_Details where teacher_id = 6 and subject_id = 3"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(DELETE_SQL)); + assertEquals(1, statement.getUpdateCount()); + } + } + + @Test + void givenPreparedStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from Demo.Teacher_Details where teacher_id = ? and subject_id = ?"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL); + preparedStatement.setInt(1, 6); + preparedStatement.setInt(2, 2); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(1, preparedStatement.getUpdateCount()); + } + } + + @Test + void givenTempTable_whenInsertIntoSelectTempTable_thenSuccess() throws SQLException { + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> { + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('12', 'David Flinch', '04-04-2014')"); + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('13', 'Stephen Hawkins', '04-07-2017')"); + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('14', 'Albert Einstein', '12-08-2020')"); + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('15', 'Leo Tolstoy', '20-08-2022')"); + }); + assertDoesNotThrow(() -> statement.execute("insert into Demo.Teacher(id, name, joining_date) " + + "select id, name, joining_date from Teacher#TEMP")); + ResultSet resultSet = statement.executeQuery("select count(id) as rows from Demo.Teacher where id in" + + " (12, 13, 14, 15)"); + resultSet.next(); + int totalRows = resultSet.getInt("rows"); + logger.info("total number of rows fetched:" + totalRows); + assertEquals(4, totalRows); + } + } + + @Test + void givenUserDefinedView_whenQueryView_thenSuccess() throws SQLException { + URL url = ClassLoader.getSystemClassLoader().getResource("UserDefinedViews.json"); + + String folderPath = url.getPath().substring(0, url.getPath().lastIndexOf('/')); + + try(Connection connection = getConnection(Map.of("Location", folderPath))) { + PreparedStatement preparedStatement = connection.prepareStatement("select teacher_name,subject_name" + + " from UserViews.View_Teacher_Details where subject_name = ?"); + preparedStatement.setString(1, "Science"); + ResultSet resultSet = preparedStatement.executeQuery(); + while(resultSet.next()) { + assertEquals("Science", resultSet.getString("subject_name")); + logger.info("Science Teacher Name:" + resultSet.getString("teacher_name")); + } + } + } + + @Test + void givenAutoCache_whenQuery_thenSuccess() throws SQLException { + URL url = ClassLoader.getSystemClassLoader().getResource("test.db"); + String folderPath = url.getPath().substring(0, url.getPath().lastIndexOf('/')); + logger.info("Cache Location:" + folderPath); + try(Connection connection = getConnection(Map.of("AutoCache", "true", "CacheLocation", folderPath))) { + PreparedStatement preparedStatement = connection.prepareStatement("select id, name from Demo.Subject"); + + ResultSet resultSet = preparedStatement.executeQuery(); + while(resultSet.next()) { + logger.info("Subject Name:" + resultSet.getString("name")); + } + } + } +} diff --git a/persistence-modules/java-harperdb/src/test/resources/UserDefinedViews.json b/persistence-modules/java-harperdb/src/test/resources/UserDefinedViews.json new file mode 100644 index 0000000000..fba67def3c --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/resources/UserDefinedViews.json @@ -0,0 +1,5 @@ +{ + "View_Teacher_Details": { + "query": "SELECT t.name as teacher_name, t.joining_date as joining_date, s.name as subject_name from Demo.Teacher_Details AS td INNER JOIN Demo.Teacher AS t ON t.id = td.teacher_id INNER JOIN Demo.Subject AS s on s.id = td.subject_id" + } +} \ No newline at end of file diff --git a/persistence-modules/java-harperdb/src/test/resources/test.db b/persistence-modules/java-harperdb/src/test/resources/test.db new file mode 100644 index 0000000000..e69de29bb2 diff --git a/persistence-modules/java-jpa-3/pom.xml b/persistence-modules/java-jpa-3/pom.xml index 0237da7ece..fa3a972623 100644 --- a/persistence-modules/java-jpa-3/pom.xml +++ b/persistence-modules/java-jpa-3/pom.xml @@ -29,8 +29,8 @@ ${h2.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -86,7 +86,7 @@ 5.4.14.Final 2.7.4 - 8.0.21 + 8.2.0 2.2 3.3.3 3.0.0 diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index b96b24582e..169a2e8fd7 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -70,8 +70,8 @@ ${javax.annotation.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -135,7 +135,7 @@ 2.1.214 4.0.0 1.3.2 - 8.0.33 + 8.2.0 \ No newline at end of file diff --git a/persistence-modules/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml index 2fc5803037..a6e0ed85e9 100644 --- a/persistence-modules/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -14,8 +14,8 @@ - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -36,8 +36,8 @@ - 5.1.6 - 3.4.2 + 8.2.0 + 4.25.0 \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 6823b460b2..41ff596ccf 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -18,6 +18,7 @@ apache-bookkeeper apache-cayenne apache-derby + atomikos blaze-persistence core-java-persistence core-java-persistence-2 @@ -59,15 +60,15 @@ solr spring-boot-persistence-2 - spring-boot-persistence-3 - spring-boot-mysql + + spring-boot-persistence spring-boot-persistence-h2 spring-boot-persistence-mongodb spring-boot-persistence-mongodb-2 spring-boot-persistence-mongodb-3 spring-data-arangodb - spring-data-cassandra + spring-data-cassandra-test spring-data-cosmosdb spring-data-couchbase-2 @@ -107,8 +108,8 @@ spring-jpa spring-jpa-2 spring-jdbc - spring-jdbc-2 - spring-jooq + spring-jdbc-2 + spring-mybatis spring-persistence-simple spring-data-yugabytedb diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index 5260bb9860..a2c8e3148d 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -52,6 +52,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.boot diff --git a/persistence-modules/read-only-transactions/pom.xml b/persistence-modules/read-only-transactions/pom.xml index 9a347fde88..c485a0d2a8 100644 --- a/persistence-modules/read-only-transactions/pom.xml +++ b/persistence-modules/read-only-transactions/pom.xml @@ -38,8 +38,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -67,7 +67,7 @@ - 8.0.21 + 8.2.0 4.0.3 5.6.1.Final 2.6.1 diff --git a/persistence-modules/rethinkdb/pom.xml b/persistence-modules/rethinkdb/pom.xml index 17c7036ed3..352be80469 100644 --- a/persistence-modules/rethinkdb/pom.xml +++ b/persistence-modules/rethinkdb/pom.xml @@ -46,8 +46,4 @@ - - 17 - - diff --git a/persistence-modules/scylladb/pom.xml b/persistence-modules/scylladb/pom.xml index f84db87742..66dd89afa9 100644 --- a/persistence-modules/scylladb/pom.xml +++ b/persistence-modules/scylladb/pom.xml @@ -37,6 +37,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml index de1836797c..6c19b92314 100644 --- a/persistence-modules/spring-boot-mysql/pom.xml +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -33,8 +33,8 @@ true - mysql - mysql-connector-java + com.mysql + mysql-connector-j @@ -56,7 +56,7 @@ - 8.0.23 + 8.2.0 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 6bca6df2b9..9b22e6902c 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -74,6 +74,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot @@ -94,8 +95,8 @@ tomcat-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -135,7 +136,7 @@ 2.0.7 1.4.6 - 8.0.33 + 8.2.0 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 3c77386ddd..123e21ce59 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -47,8 +47,8 @@ tomcat-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -72,7 +72,7 @@ 2.23.0 2.0.1.Final - 8.0.31 + 8.2.0 com.baeldung.boot.Application diff --git a/persistence-modules/spring-data-cassandra-2/pom.xml b/persistence-modules/spring-data-cassandra-2/pom.xml index 01b5ce5ed6..6532da7f95 100644 --- a/persistence-modules/spring-data-cassandra-2/pom.xml +++ b/persistence-modules/spring-data-cassandra-2/pom.xml @@ -99,7 +99,6 @@ - 11 3.4.15 1.19.0 1.1.0 diff --git a/persistence-modules/spring-data-cosmosdb/pom.xml b/persistence-modules/spring-data-cosmosdb/pom.xml index 30dc4f999c..fbd4af9456 100644 --- a/persistence-modules/spring-data-cosmosdb/pom.xml +++ b/persistence-modules/spring-data-cosmosdb/pom.xml @@ -32,6 +32,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/persistence-modules/spring-data-elasticsearch/pom.xml b/persistence-modules/spring-data-elasticsearch/pom.xml index 6535b9ac4b..b8edae68d3 100644 --- a/persistence-modules/spring-data-elasticsearch/pom.xml +++ b/persistence-modules/spring-data-elasticsearch/pom.xml @@ -40,7 +40,7 @@ org.projectlombok lombok - 1.18.28 + ${lombok.version} org.springframework.boot @@ -60,7 +60,7 @@ 5.1.2 8.9.0 - 2.15.2 + 2.16.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index 1282d1d8a0..62bf7f0314 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -36,9 +36,9 @@ ${jta.version} - mysql - mysql-connector-java - 3.1.12 + com.mysql + mysql-connector-j + ${mysql.version} com.google.guava @@ -85,6 +85,7 @@ 9.0.0.M26 1.1 + 8.2.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index 23134ec02d..8c588405f7 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -2,9 +2,7 @@ ### Relevant Articles: -- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Performance Difference Between save() and saveAll() in Spring Data](https://www.baeldung.com/spring-data-save-saveall) -- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) - [How to Access EntityManager with Spring Data](https://www.baeldung.com/spring-data-entitymanager) - [Difference Between JPA and Spring Data JPA](https://www.baeldung.com/spring-data-jpa-vs-jpa) - [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop) diff --git a/persistence-modules/spring-data-jpa-repo-2/pom.xml b/persistence-modules/spring-data-jpa-repo-2/pom.xml index 8186a0f7a5..e39458449c 100644 --- a/persistence-modules/spring-data-jpa-repo-2/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-2/pom.xml @@ -42,11 +42,6 @@ com.querydsl querydsl-jpa - - com.google.guava - guava - ${guava.version} - diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql deleted file mode 100644 index 0ba0ba0694..0000000000 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql +++ /dev/null @@ -1 +0,0 @@ -DELETE FROM "movie"; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql deleted file mode 100644 index 0eb9638f43..0000000000 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100); diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 43097a8c1e..9587f544f9 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -3,6 +3,7 @@ This module contains articles about repositories in Spring Data JPA ### Relevant Articles: +- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) - [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) - [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) @@ -10,6 +11,8 @@ This module contains articles about repositories in Spring Data JPA - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) +- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) + - More articles: [[--> next]](../spring-data-jpa-repo-2) ### Eclipse Config diff --git a/persistence-modules/spring-data-jpa-repo/pom.xml b/persistence-modules/spring-data-jpa-repo/pom.xml index 26fff365a1..4ce19d83d0 100644 --- a/persistence-modules/spring-data-jpa-repo/pom.xml +++ b/persistence-modules/spring-data-jpa-repo/pom.xml @@ -27,8 +27,8 @@ spring-boot-starter-data-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.postgresql @@ -42,6 +42,11 @@ org.springframework spring-oxm + + com.google.guava + guava + ${guava.version} + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java similarity index 87% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java index 6833c4c556..27ebcf5875 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java @@ -1,8 +1,13 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; -import javax.persistence.*; import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + @Entity public class Foo implements Serializable { @Id diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java similarity index 83% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java index cb09a92b82..98084240ac 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java similarity index 82% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java index 20a81e7bfa..6ee74fe26c 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java @@ -1,8 +1,9 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; public interface IFooDAO extends JpaRepository { diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java similarity index 50% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java index 8ce6a2d1ae..6c4d36710c 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; public interface IFooService { Foo create(Foo foo); diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java similarity index 93% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java index f73ea94658..f3c9301bcf 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java @@ -1,6 +1,9 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; + +import java.util.Properties; + +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; @@ -16,15 +19,14 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; -import java.util.Properties; +import com.google.common.base.Preconditions; @Configuration @PropertySource("classpath:persistence.properties") -@ComponentScan("com.baeldung.spring.data.persistence.repository") +@ComponentScan("com.baeldung.repository") //@ImportResource("classpath*:*springDataConfig.xml") @EnableTransactionManagement -@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository") +@EnableJpaRepositories(basePackages = "com.baeldung.repository") public class PersistenceConfig { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java similarity index 99% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java index 57befb5943..06e75222a3 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java @@ -1,11 +1,12 @@ package com.baeldung.spring.data.persistence.like.repository; -import com.baeldung.spring.data.persistence.like.model.Movie; +import java.util.List; + import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; -import java.util.List; +import com.baeldung.spring.data.persistence.like.model.Movie; public interface MovieRepository extends CrudRepository { diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-repo/src/main/resources/persistence.properties new file mode 100644 index 0000000000..05cb7a13b9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/persistence.properties @@ -0,0 +1,9 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +# hibernate.X +hibernate.hbm2ddl.auto=create-drop +hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml b/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml similarity index 84% rename from persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml rename to persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml index b2616d9eae..e581d514a4 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml @@ -7,5 +7,5 @@ http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" > - + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java similarity index 92% rename from persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java index 21990afb5e..9362b4c338 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java @@ -1,4 +1,6 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; + +import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; @@ -7,8 +9,6 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import javax.sql.DataSource; - @RunWith(SpringRunner.class) @ContextConfiguration(classes = PersistenceConfig.class) public class FooServiceIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java index 291926c127..dcb87a26a6 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java @@ -1,7 +1,12 @@ package com.baeldung.spring.data.persistence.like; -import com.baeldung.spring.data.persistence.like.model.Movie; -import com.baeldung.spring.data.persistence.like.repository.MovieRepository; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; + +import java.util.List; + +import javax.sql.DataSource; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,11 +14,8 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; -import javax.sql.DataSource; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; +import com.baeldung.spring.data.persistence.like.model.Movie; +import com.baeldung.spring.data.persistence.like.repository.MovieRepository; @RunWith(SpringRunner.class) @Sql(scripts = { "/test-movie-data.sql" }) diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties index f9497c8f37..6f93e7d79d 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties @@ -1,2 +1,2 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file +#spring.jpa.hibernate.ddl-auto=update +#spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql new file mode 100644 index 0000000000..e2e70a6a74 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql @@ -0,0 +1 @@ +DELETE FROM movie; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql new file mode 100644 index 0000000000..3b706f14e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql @@ -0,0 +1,7 @@ +INSERT INTO movie(id,title,director,rating,duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132); +INSERT INTO movie(id,title,director,rating,duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181); +INSERT INTO movie(id,title,director,rating,duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123); +INSERT INTO movie(id,title,director,rating,duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112); +INSERT INTO movie(id,title,director,rating,duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102); +INSERT INTO movie(id,title,director,rating,duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128); +INSERT INTO movie(id,title,director,rating,duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100); diff --git a/persistence-modules/spring-data-mongodb-reactive/pom.xml b/persistence-modules/spring-data-mongodb-reactive/pom.xml index 85c9a4c4b6..46b2e8067f 100644 --- a/persistence-modules/spring-data-mongodb-reactive/pom.xml +++ b/persistence-modules/spring-data-mongodb-reactive/pom.xml @@ -35,6 +35,7 @@ org.projectlombok lombok + ${lombok.version} io.projectreactor diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 052935e215..382cdf83f5 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -27,6 +27,7 @@ org.projectlombok lombok + ${lombok.version} io.projectreactor diff --git a/persistence-modules/spring-data-rest-querydsl/pom.xml b/persistence-modules/spring-data-rest-querydsl/pom.xml index dc1cf64006..0fe9d381cf 100644 --- a/persistence-modules/spring-data-rest-querydsl/pom.xml +++ b/persistence-modules/spring-data-rest-querydsl/pom.xml @@ -28,8 +28,8 @@ spring-boot-starter-data-jpa - mysql - mysql-connector-java + com.mysql + mysql-connector-j com.querydsl diff --git a/persistence-modules/spring-data-shardingsphere/pom.xml b/persistence-modules/spring-data-shardingsphere/pom.xml index c1ca313038..117a3ae7fe 100644 --- a/persistence-modules/spring-data-shardingsphere/pom.xml +++ b/persistence-modules/spring-data-shardingsphere/pom.xml @@ -17,7 +17,7 @@ 5.3.2 - 8.0.33 + 8.2.0 @@ -43,8 +43,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index 306c4995d2..61b253d0d2 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -37,8 +37,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} runtime @@ -79,7 +79,7 @@ 3.21.0-GA 3.6.10.Final - 5.1.40 + 8.2.0 8.5.8 diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index e559fe1394..3ad8f791df 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -99,8 +99,8 @@ ${hsqldb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -131,9 +131,9 @@ 1.10.6.RELEASE 4.2.1.RELEASE - 5.2.10.Final + 5.6.15.Final 5.8.2.Final - 8.0.7-dmr + 8.2.0 9.0.0.M26 1.1 2.3.0.1 diff --git a/persistence-modules/spring-hibernate-6/pom.xml b/persistence-modules/spring-hibernate-6/pom.xml index a13117e68c..3cd69a963e 100644 --- a/persistence-modules/spring-hibernate-6/pom.xml +++ b/persistence-modules/spring-hibernate-6/pom.xml @@ -84,8 +84,8 @@ ${hsqldb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -102,7 +102,7 @@ 6.1.3 6.2.8.Final - 8.0.7-dmr + 8.2.0 9.0.80 diff --git a/persistence-modules/spring-jdbc/pom.xml b/persistence-modules/spring-jdbc/pom.xml index 08e43e8292..1cf4c141b3 100644 --- a/persistence-modules/spring-jdbc/pom.xml +++ b/persistence-modules/spring-jdbc/pom.xml @@ -27,8 +27,8 @@ h2 - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 10e44c0ce4..61950d9c93 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -54,8 +54,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} runtime @@ -117,7 +117,7 @@ 6.0.6 3.29.2-GA - 8.0.33 + 8.2.0 3.1.0 6.0.0 diff --git a/pom.xml b/pom.xml index 7099dd8cbc..ac7d12a5a0 100644 --- a/pom.xml +++ b/pom.xml @@ -701,7 +701,7 @@ apache-kafka apache-libraries-2 apache-libraries - apache-olingo + apache-olingo apache-poi-2 apache-poi-3 apache-poi @@ -710,7 +710,6 @@ apache-velocity asciidoctor asm - atomikos atomix aws-modules azure @@ -727,7 +726,7 @@ dozer drools dubbo - + feign gcp-firebase geotools google-auto-project @@ -757,7 +756,7 @@ jersey jetbrains jgit - jhipster-6 + jib jmeter jmh @@ -801,7 +800,7 @@ lombok-modules lucene mapstruct - maven-modules + mesos-marathon messaging-modules metrics @@ -818,6 +817,7 @@ pdf performance-tests persistence-modules + persistence-modules/java-harperdb persistence-modules/spring-data-neo4j protobuffer quarkus-modules @@ -836,19 +836,19 @@ spring-activiti spring-actuator spring-aop-2 - spring-aop + spring-batch-2 spring-batch spring-boot-modules spring-boot-rest spring-cloud-modules/spring-cloud-azure spring-cloud-modules/spring-cloud-circuit-breaker - spring-cloud-modules/spring-cloud-contract - spring-cloud-modules/spring-cloud-data-flow + + spring-cloud-modules/spring-cloud-eureka spring-cloud-modules/spring-cloud-netflix-feign spring-cloud-modules/spring-cloud-security - spring-cloud-modules/spring-cloud-stream-starters + spring-cloud-modules/spring-cloud-zuul-eureka-integration spring-core-2 spring-core-3 @@ -856,18 +856,19 @@ spring-core spring-credhub spring-cucumber - spring-di-2 + spring-di-3 spring-di-4 spring-di spring-drools spring-ejb-modules spring-exceptions - spring-integration + spring-jenkins-pipeline spring-jersey spring-jinq spring-kafka-2 + spring-kafka-3 spring-kafka spring-katharsis spring-mobile @@ -889,26 +890,27 @@ spring-vault spring-web-modules spring-websockets - static-analysis - tablesaw + + tensorflow-java testing-modules testing-modules/mockito-simple + timefold-solver vaadin vavr-modules vertx-modules web-modules webrtc - xml-2 + xml xstream UTF-8 - 11 - 11 - 11 + 17 + 17 + 17 @@ -946,7 +948,7 @@ apache-kafka apache-libraries-2 apache-libraries - apache-olingo + apache-olingo apache-poi-2 apache-poi-3 apache-poi @@ -955,7 +957,6 @@ apache-velocity asciidoctor asm - atomikos atomix aws-modules azure @@ -972,7 +973,7 @@ dozer drools dubbo - + feign gcp-firebase geotools google-auto-project @@ -1002,7 +1003,7 @@ jersey jetbrains jgit - jhipster-6 + jib jmeter jmh @@ -1046,7 +1047,7 @@ lombok-modules lucene mapstruct - maven-modules + mesos-marathon messaging-modules metrics @@ -1081,19 +1082,19 @@ spring-activiti spring-actuator spring-aop-2 - spring-aop + spring-batch-2 spring-batch spring-boot-modules spring-boot-rest spring-cloud-modules/spring-cloud-azure spring-cloud-modules/spring-cloud-circuit-breaker - spring-cloud-modules/spring-cloud-contract - spring-cloud-modules/spring-cloud-data-flow + + spring-cloud-modules/spring-cloud-eureka spring-cloud-modules/spring-cloud-netflix-feign spring-cloud-modules/spring-cloud-security - spring-cloud-modules/spring-cloud-stream-starters + spring-cloud-modules/spring-cloud-zuul-eureka-integration spring-core-2 spring-core-3 @@ -1101,14 +1102,14 @@ spring-core spring-credhub spring-cucumber - spring-di-2 + spring-di-3 spring-di-4 spring-di spring-drools spring-ejb-modules spring-exceptions - spring-integration + spring-jenkins-pipeline spring-jersey spring-jinq @@ -1134,26 +1135,27 @@ spring-vault spring-web-modules spring-websockets - static-analysis - tablesaw + + tensorflow-java testing-modules testing-modules/mockito-simple + timefold-solver vaadin vavr-modules vertx-modules web-modules webrtc - xml-2 + xml xstream UTF-8 - 11 - 11 - 11 + 17 + 17 + 17 @@ -1223,7 +1225,7 @@ 1.2 2.3.3 1.2 - 2.15.2 + 2.16.0 1.5 1.9.2 5.9.2 @@ -1234,7 +1236,7 @@ 3.12.2 3.3.0 3.21.0 - 1.18.28 + 1.18.30 2.1.214 32.1.3-jre 3.3.0 diff --git a/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml index 95916932a1..f1fe9eec5c 100644 --- a/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -66,8 +66,7 @@ - 3.8.1 - 3.8.1 + 4.25.0 \ No newline at end of file diff --git a/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml b/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml index 74deab3558..c3ee41223f 100644 --- a/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml +++ b/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml @@ -253,10 +253,7 @@ 1.17.2 - 11 0.12.1 - 11 - 11 3.1.0 0.9.11 2.0.8 diff --git a/reactive-systems/inventory-service/pom.xml b/reactive-systems/inventory-service/pom.xml index 4aeec24922..baf5151fdc 100644 --- a/reactive-systems/inventory-service/pom.xml +++ b/reactive-systems/inventory-service/pom.xml @@ -31,6 +31,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/reactive-systems/order-service/pom.xml b/reactive-systems/order-service/pom.xml index b9e5d36d3a..b6cfb70678 100644 --- a/reactive-systems/order-service/pom.xml +++ b/reactive-systems/order-service/pom.xml @@ -31,6 +31,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/reactive-systems/shipping-service/pom.xml b/reactive-systems/shipping-service/pom.xml index 5fac674bbc..8f94dabdea 100644 --- a/reactive-systems/shipping-service/pom.xml +++ b/reactive-systems/shipping-service/pom.xml @@ -31,6 +31,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/saas-modules/stripe/pom.xml b/saas-modules/stripe/pom.xml index 44bc5be4a8..77bb912b7b 100644 --- a/saas-modules/stripe/pom.xml +++ b/saas-modules/stripe/pom.xml @@ -27,6 +27,7 @@ org.projectlombok lombok + ${lombok.version} com.stripe diff --git a/security-modules/cas/cas-secured-app/pom.xml b/security-modules/cas/cas-secured-app/pom.xml index 7c4864b1c0..b5ac123b21 100644 --- a/security-modules/cas/cas-secured-app/pom.xml +++ b/security-modules/cas/cas-secured-app/pom.xml @@ -41,8 +41,8 @@ spring-boot-starter-data-jpa - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java index 687a827448..e453f33d5e 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java @@ -4,9 +4,11 @@ import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.jjwtfun.service.SecretService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRepository; @@ -21,19 +23,19 @@ import java.io.IOException; import java.util.Arrays; @Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Autowired - CsrfTokenRepository jwtCsrfTokenRepository; + private CsrfTokenRepository jwtCsrfTokenRepository; @Autowired - SecretService secretService; + private SecretService secretService; // ordered so we can use binary search below - private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" }; + private final String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" }; - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) .csrf() .csrfTokenRepository(jwtCsrfTokenRepository) @@ -42,6 +44,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { .authorizeRequests() .antMatchers("/**") .permitAll(); + + return http.build(); } private class JwtCsrfValidatorFilter extends OncePerRequestFilter { diff --git a/security-modules/sql-injection-samples/pom.xml b/security-modules/sql-injection-samples/pom.xml index 7953e43ebe..37779e0d14 100644 --- a/security-modules/sql-injection-samples/pom.xml +++ b/security-modules/sql-injection-samples/pom.xml @@ -38,6 +38,7 @@ org.projectlombok lombok + ${lombok.version} provided diff --git a/spring-4/pom.xml b/spring-4/pom.xml index 681747c1f6..9a50319d13 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -57,6 +57,7 @@ org.projectlombok lombok + ${lombok.version} provided @@ -120,7 +121,7 @@ 1.0.1 3.6 2.4.0 - 4.0.3 + 5.1.0 2.17.1 diff --git a/spring-5-webflux-2/pom.xml b/spring-5-webflux-2/pom.xml index 34cbda6c18..efb99e06d5 100644 --- a/spring-5-webflux-2/pom.xml +++ b/spring-5-webflux-2/pom.xml @@ -86,6 +86,7 @@ com.squareup.okhttp3 mockwebserver + 4.12.0 diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index 69de83c227..8a381b250a 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -46,6 +46,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.boot @@ -74,6 +75,7 @@ com.squareup.okhttp3 mockwebserver + 4.12.0 diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 1ac696e7bd..65f1b77520 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -143,7 +143,7 @@ 1.0 1.5.6 ${project.build.directory}/generated-snippets - 4.0.3 + 5.1.0 \ No newline at end of file diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index 20b0ef6d1c..bca0030729 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -77,7 +77,7 @@ 5.8 4.0.0 4.0.2 - 2.14.2 + 2.16.0 4.5.14 1.5.3 com.baeldung.batchtesting.SpringBatchApplication diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 433f23f4ba..eaf04cf015 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -42,7 +42,7 @@ spring-boot-exceptions spring-boot-flowable spring-boot-graphql - spring-boot-groovy + spring-boot-jasypt spring-boot-jsp diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index c85488d44b..e48b232a52 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -79,6 +79,7 @@ org.projectlombok lombok + ${lombok.version} true diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsLiveTest.java similarity index 80% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsLiveTest.java index 4130b6cb6b..9198cc1f68 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomCassandraConnectionDetailsConfiguration; @@ -22,8 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-cassandra.properties"}) @ActiveProfiles("cassandra") -public class CassandraConnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(CassandraConnectionDetailsIntegrationTest.class); +public class CassandraConnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(CassandraConnectionDetailsLiveTest.class); @Autowired private CassandraTemplate cassandraTemplate; @Test diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsLiveTest.java similarity index 77% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsLiveTest.java index 454aad4c6c..6f19382950 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomCouchBaseConnectionDetailsConfiguration; @@ -20,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-couch.properties"}) @ActiveProfiles("couch") -public class CouchbaseConnectionDetailsIntegrationTest { +public class CouchbaseConnectionDetailsLiveTest { @Autowired private Cluster cluster; @Test diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsLiveTest.java similarity index 81% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsLiveTest.java index ee698cd6ea..10d0e9d019 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomElasticsearchConnectionDetailsConfiguration; @@ -24,8 +29,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-elastic.properties"}) @ActiveProfiles("elastic") -public class ElasticsearchConnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConnectionDetailsIntegrationTest.class); +public class ElasticsearchConnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConnectionDetailsLiveTest.class); @Autowired private ElasticsearchTemplate elasticsearchTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsLiveTest.java similarity index 79% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsLiveTest.java index 748bc27b0b..b074eb9bfd 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.JdbcConnectionDetailsConfiguration; @@ -25,8 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-jdbc.properties"}) @ActiveProfiles("jdbc") -public class JdbcConnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(JdbcConnectionDetailsIntegrationTest.class); +public class JdbcConnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(JdbcConnectionDetailsLiveTest.class); @Autowired private JdbcTemplate jdbcTemplate; @Test diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsLiveTest.java similarity index 78% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsLiveTest.java index bc0e174b3f..f23e610d3a 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomKafkaConnectionDetailsConfiguration; @@ -21,7 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-kafka.properties"}) @ActiveProfiles("kafka") -public class KafkaConnectionDetailsIntegrationTest { +public class KafkaConnectionDetailsLiveTest { @Autowired private KafkaTemplate kafkaTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsLiveTest.java similarity index 85% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsLiveTest.java index 868ebfea98..e2dceff9ec 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.MongoDBConnectionDetailsConfiguration; @@ -26,7 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-mongo.properties"}) @ActiveProfiles("mongo") -public class MongoDBConnectionDetailsIntegrationTest { +public class MongoDBConnectionDetailsLiveTest { @Autowired private MongoTemplate mongoTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsLiveTest.java similarity index 81% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsLiveTest.java index 943ed7bdea..8eb9ec44d2 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomNeo4jConnectionDetailsConfiguration; @@ -22,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-neo4j.properties"}) @ActiveProfiles("neo4j") -public class Neo4jConnectionDetailsIntegrationTest { +public class Neo4jConnectionDetailsLiveTest { @Autowired private Neo4jTemplate neo4jTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsLiveTest.java similarity index 80% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsLiveTest.java index 5f8c8349fb..460a48e7ff 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.R2dbcPostgresConnectionDetailsConfiguration; @@ -20,8 +25,8 @@ import java.util.List; @Import(R2dbcPostgresConnectionDetailsConfiguration.class) @TestPropertySource(locations = {"classpath:connectiondetails/application-r2dbc.properties"}) @ActiveProfiles("r2dbc") -public class R2dbcConnectionDetailsIntegrationTest { - Logger logger = LoggerFactory.getLogger(R2dbcConnectionDetailsIntegrationTest.class); +public class R2dbcConnectionDetailsLiveTest { + Logger logger = LoggerFactory.getLogger(R2dbcConnectionDetailsLiveTest.class); @Autowired private R2dbcEntityTemplate r2dbcEntityTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsLiveTest.java similarity index 85% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsLiveTest.java index 9e10973ed7..5f7eb055eb 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.RabbitMQConnectionDetailsConfiguration; @@ -25,9 +30,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @Import(RabbitMQConnectionDetailsConfiguration.class) @TestPropertySource(locations = {"classpath:connectiondetails/application-rabbitmq.properties"}) @ActiveProfiles("rabbitmq") -public class RabbitmqConnectionDetailsIntegrationTest { +public class RabbitmqConnectionDetailsLiveTest { - private static final Logger logger = LoggerFactory.getLogger(RabbitmqConnectionDetailsIntegrationTest.class); + private static final Logger logger = LoggerFactory.getLogger(RabbitmqConnectionDetailsLiveTest.class); @Autowired private RabbitTemplate rabbitTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsLiveTest.java similarity index 76% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsLiveTest.java index 5dbd2d6c03..919f968323 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.RedisConnectionDetailsConfiguration; @@ -20,8 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @Import(RedisConnectionDetailsConfiguration.class) @TestPropertySource(locations = {"classpath:connectiondetails/application-redis.properties"}) @ActiveProfiles("redis") -public class RedisCacheConnnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(RedisCacheConnnectionDetailsIntegrationTest.class); +public class RedisCacheConnnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(RedisCacheConnnectionDetailsLiveTest.class); @Autowired RedisTemplate redisTemplate; diff --git a/spring-boot-modules/spring-boot-cassandre/pom.xml b/spring-boot-modules/spring-boot-cassandre/pom.xml index e2964183d2..3834d7b88c 100644 --- a/spring-boot-modules/spring-boot-cassandre/pom.xml +++ b/spring-boot-modules/spring-boot-cassandre/pom.xml @@ -40,7 +40,6 @@ - 11 4.2.1 5.0.7 2.5.1 diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java new file mode 100644 index 0000000000..4a780ac17a --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.entitydtodifferences; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java new file mode 100644 index 0000000000..66cecacd9b --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java @@ -0,0 +1,39 @@ +package com.baeldung.entitydtodifferences.controller; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.mapper.UserMapper; +import com.baeldung.entitydtodifferences.repository.UserRepository; + +@RestController +@RequestMapping("/users") +public class UserController { + + private final UserRepository userRepository; + + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping + public List getUsers() { + return userRepository.findAll() + .stream() + .map(UserMapper::toDto) + .collect(Collectors.toList()); + } + + @PostMapping + public UserResponseDto createUser(@RequestBody UserCreationDto userCreationDto) { + return UserMapper.toDto(userRepository.save(UserMapper.toEntity(userCreationDto))); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java new file mode 100644 index 0000000000..a5ee25f105 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java @@ -0,0 +1,30 @@ +package com.baeldung.entitydtodifferences.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class BookDto { + + @JsonProperty("NAME") + private final String name; + + @JsonProperty("AUTHOR") + private final String author; + + // Default constructor for Jackson deserialization + public BookDto() { + this(null, null); + } + + public BookDto(String name, String author) { + this.name = name; + this.author = author; + } + + public String getName() { + return name; + } + + public String getAuthor() { + return author; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java new file mode 100644 index 0000000000..0859c042cf --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java @@ -0,0 +1,48 @@ +package com.baeldung.entitydtodifferences.dto; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class UserCreationDto { + + @JsonProperty("FIRST_NAME") + private final String firstName; + + @JsonProperty("LAST_NAME") + private final String lastName; + + @JsonProperty("ADDRESS") + private final String address; + + @JsonProperty("BOOKS") + private final List books; + + // Default constructor for Jackson deserialization + public UserCreationDto() { + this(null, null, null, null); + } + + public UserCreationDto(String firstName, String lastName, String address, List books) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + this.books = books; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getAddress() { + return address; + } + + public List getBooks() { + return books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java new file mode 100644 index 0000000000..910689dd41 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java @@ -0,0 +1,48 @@ +package com.baeldung.entitydtodifferences.dto; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class UserResponseDto { + + @JsonProperty("ID") + private final Long id; + + @JsonProperty("FIRST_NAME") + private final String firstName; + + @JsonProperty("LAST_NAME") + private final String lastName; + + @JsonProperty("BOOKS") + private final List books; + + // Default constructor for Jackson deserialization + public UserResponseDto() { + this(null, null, null, null); + } + + public UserResponseDto(Long id, String firstName, String lastName, List books) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.books = books; + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public List getBooks() { + return books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java new file mode 100644 index 0000000000..88e895467a --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java @@ -0,0 +1,39 @@ +package com.baeldung.entitydtodifferences.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "books") +public class Book { + + @Id + private String name; + private String author; + + // Default constructor for JPA deserialization + public Book() { + } + + public Book(String name, String author) { + this.name = name; + this.author = author; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java new file mode 100644 index 0000000000..6a404e9f1f --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java @@ -0,0 +1,90 @@ +package com.baeldung.entitydtodifferences.entity; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + private String lastName; + private String address; + + @OneToMany(cascade = CascadeType.ALL) + private List books; + + // Default constructor for JPA deserialization + public User() { + } + + public User(String firstName, String lastName, String address, List books) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + this.books = books; + } + + public String getNameOfMostOwnedBook() { + Map bookOwnershipCount = books.stream() + .collect(Collectors.groupingBy(Book::getName, Collectors.counting())); + return bookOwnershipCount.entrySet() + .stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(null); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java new file mode 100644 index 0000000000..0c6899f98b --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java @@ -0,0 +1,34 @@ +package com.baeldung.entitydtodifferences.mapper; + +import java.util.stream.Collectors; + +import com.baeldung.entitydtodifferences.dto.BookDto; +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; + +public class UserMapper { + + public static UserResponseDto toDto(User entity) { + return new UserResponseDto(entity.getId(), entity.getFirstName(), entity.getLastName(), entity.getBooks() + .stream() + .map(UserMapper::toDto) + .collect(Collectors.toList())); + } + + public static User toEntity(UserCreationDto dto) { + return new User(dto.getFirstName(), dto.getLastName(), dto.getAddress(), dto.getBooks() + .stream() + .map(UserMapper::toEntity) + .collect(Collectors.toList())); + } + + public static BookDto toDto(Book entity) { + return new BookDto(entity.getName(), entity.getAuthor()); + } + + public static Book toEntity(BookDto dto) { + return new Book(dto.getName(), dto.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java new file mode 100644 index 0000000000..4529de698e --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.entitydtodifferences.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.entitydtodifferences.entity.User; + +@Repository +public interface UserRepository extends JpaRepository { + +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..839bb381ec --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.entitydtodifferences; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ApplicationIntegrationTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java new file mode 100644 index 0000000000..83e359e378 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java @@ -0,0 +1,93 @@ +package com.baeldung.entitydtodifferences.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; +import com.baeldung.entitydtodifferences.repository.UserRepository; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest +@AutoConfigureMockMvc +public class UserControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + + @Autowired + private ObjectMapper objectMapper; + + @BeforeEach + public void beforeEach() { + userRepository.deleteAll(); + } + + @Test + public void givenUsersAreExisting_whenGetUsers_thenUsersAreReturned() throws Exception { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User savedUser = userRepository.save(new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2))); + String expectedJson = String.format( + "[{\"ID\":%s,\"FIRST_NAME\":\"John\",\"LAST_NAME\":\"Doe\",\"BOOKS\":[{\"NAME\":\"Book1\",\"AUTHOR\":\"Author1\"},{\"NAME\":\"Book2\",\"AUTHOR\":\"Author2\"}]}]", + savedUser.getId()); + //when + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/users") + .contentType(MediaType.APPLICATION_JSON)) + .andReturn(); + //then + assertEquals(expectedJson, result.getResponse() + .getContentAsString()); + } + + @Test + public void givenValidUser_whenPostUser_thenUserIsCreated() throws Exception { + //given + String user = "{\"FIRST_NAME\":\"John\",\"LAST_NAME\":\"Doe\",\"BOOKS\":[{\"NAME\":\"Book1\",\"AUTHOR\":\"Author1\"},{\"NAME\":\"Book2\",\"AUTHOR\":\"Author2\"}]}"; + //when + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/users") + .content(user) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andReturn(); + JsonNode responseJson = objectMapper.readTree(result.getResponse() + .getContentAsString()); + //then + assertEquals("John", responseJson.get("FIRST_NAME") + .asText()); + assertEquals("Doe", responseJson.get("LAST_NAME") + .asText()); + assertTrue(responseJson.has("BOOKS")); + JsonNode booksArray = responseJson.get("BOOKS"); + assertEquals(2, booksArray.size()); + assertEquals("Book1", booksArray.get(0) + .get("NAME") + .asText()); + assertEquals("Author1", booksArray.get(0) + .get("AUTHOR") + .asText()); + assertEquals("Book2", booksArray.get(1) + .get("NAME") + .asText()); + assertEquals("Author2", booksArray.get(1) + .get("AUTHOR") + .asText()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java new file mode 100644 index 0000000000..60e229b7c9 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.entitydtodifferences.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.Test; + +public class BookUnitTest { + + @Test + public void whenBookInitialized_thenInitializedCorrectly() { + //when + Book book = new Book("Book1", "Author1"); + //then + assertNotNull(book); + assertEquals("Book1", book.getName()); + assertEquals("Author1", book.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java new file mode 100644 index 0000000000..0d1efe7129 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.entitydtodifferences.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; + +public class UserUnitTest { + + @Test + public void whenUserInitialized_thenInitializedCorrectly() { + //when + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2)); + //then + assertNotNull(user); + assertEquals("John", user.getFirstName()); + assertEquals("Doe", user.getLastName()); + assertEquals("123 Main St", user.getAddress()); + assertEquals(2, user.getBooks() + .size()); + } + + @Test + public void givenUserOwningMultipleBooks_whenGetNameOfMostOwnedBook_thenComputedCorrectly() { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + Book book3 = new Book("Book2", "Author3"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2, book3)); + //when + String mostOwnedBook = user.getNameOfMostOwnedBook(); + //then + assertEquals("Book2", mostOwnedBook); + } + + @Test + public void givenUserWithNoBooks_henGetNameOfMostOwnedBook_thenReturnedNull() { + //given + User user = new User("John", "Doe", "123 Main St", Collections.emptyList()); + //when + String mostOwnedBook = user.getNameOfMostOwnedBook(); + //then + assertNull(mostOwnedBook); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java new file mode 100644 index 0000000000..5154898877 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.entitydtodifferences.mapper; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.entitydtodifferences.dto.BookDto; +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; + +public class UserMapperUnitTest { + + @Test + public void givenUserEntity_whenMappedToDto_thenMappedCorrectly() { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2)); + //when + UserResponseDto userDto = UserMapper.toDto(user); + //then + assertEquals(user.getId(), userDto.getId()); + assertEquals(user.getFirstName(), userDto.getFirstName()); + assertEquals(user.getLastName(), userDto.getLastName()); + List bookDtos = userDto.getBooks(); + assertEquals(2, bookDtos.size()); + assertEquals(book1.getName(), bookDtos.get(0) + .getName()); + assertEquals(book1.getAuthor(), bookDtos.get(0) + .getAuthor()); + assertEquals(book2.getName(), bookDtos.get(1) + .getName()); + assertEquals(book2.getAuthor(), bookDtos.get(1) + .getAuthor()); + } + + @Test + public void givenUserDto_whenMappedToEntity_thenMappedCorrectly() { + //given + BookDto bookDto1 = new BookDto("Book3", "Author3"); + BookDto bookDto2 = new BookDto("Book4", "Author4"); + UserCreationDto userDto = new UserCreationDto("Jane", "Doe", "456 Oak St", Arrays.asList(bookDto1, bookDto2)); + //when + User user = UserMapper.toEntity(userDto); + //then + assertEquals(user.getFirstName(), userDto.getFirstName()); + assertEquals(user.getLastName(), userDto.getLastName()); + assertEquals(user.getAddress(), userDto.getAddress()); + List books = user.getBooks(); + assertEquals(2, books.size()); + assertEquals(bookDto1.getName(), books.get(0) + .getName()); + assertEquals(bookDto1.getAuthor(), books.get(0) + .getAuthor()); + assertEquals(bookDto2.getName(), books.get(1) + .getName()); + assertEquals(bookDto2.getAuthor(), books.get(1) + .getAuthor()); + } + + @Test + public void givenBookEntity_whenMappedToDto_thenMappedCorrectly() { + //given + Book book = new Book("Book5", "Author5"); + //when + BookDto bookDto = UserMapper.toDto(book); + //then + assertEquals(book.getName(), bookDto.getName()); + assertEquals(book.getAuthor(), bookDto.getAuthor()); + } + + @Test + public void givenBookDto_whenMappedToEntity_thenMappedCorrectly() { + //given + BookDto bookDto = new BookDto("Book6", "Author6"); + //when + Book book = UserMapper.toEntity(bookDto); + //then + assertEquals(bookDto.getName(), book.getName()); + assertEquals(bookDto.getAuthor(), book.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index 8e6619dce4..b8f0347453 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -6,4 +6,4 @@ - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) - [BootstrapMode for JPA Repositories](https://www.baeldung.com/jpa-bootstrap-mode) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - +- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java diff --git a/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java rename to spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java diff --git a/spring-boot-modules/spring-boot-data-3/pom.xml b/spring-boot-modules/spring-boot-data-3/pom.xml index 6c2edbb864..4afafe3c19 100644 --- a/spring-boot-modules/spring-boot-data-3/pom.xml +++ b/spring-boot-modules/spring-boot-data-3/pom.xml @@ -30,8 +30,8 @@ ${aws-secretsmanager-jdbc.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index aa745b77a2..49a6eedbed 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -8,7 +8,6 @@ This module contains articles about Spring Boot with Spring Data - [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) - [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) - [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) -- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) - [Guide To Running Logic on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) diff --git a/spring-boot-modules/spring-boot-documentation/pom.xml b/spring-boot-modules/spring-boot-documentation/pom.xml index 3ac2799258..30a82660af 100644 --- a/spring-boot-modules/spring-boot-documentation/pom.xml +++ b/spring-boot-modules/spring-boot-documentation/pom.xml @@ -95,7 +95,7 @@ 2.2.11 0.14.0 0.14.0 - 1.18.3 + 1.19.3 diff --git a/spring-boot-modules/spring-boot-graphql/pom.xml b/spring-boot-modules/spring-boot-graphql/pom.xml index d3c122709d..b3f27f1b84 100644 --- a/spring-boot-modules/spring-boot-graphql/pom.xml +++ b/spring-boot-modules/spring-boot-graphql/pom.xml @@ -59,6 +59,7 @@ org.projectlombok lombok + ${lombok.version} com.h2database diff --git a/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java b/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java index 87bebf644c..a2e63a96f8 100644 --- a/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java @@ -1,6 +1,5 @@ package com.baeldung.graphql.intro; -import com.baeldung.graphql.intro.GraphqlApplication; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot-groovy/pom.xml b/spring-boot-modules/spring-boot-groovy/pom.xml index 151160bde5..677e07db2d 100644 --- a/spring-boot-modules/spring-boot-groovy/pom.xml +++ b/spring-boot-modules/spring-boot-groovy/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.app spring-boot-groovy @@ -10,9 +10,10 @@ Spring Boot Todo Application with Groovy - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -25,7 +26,7 @@ spring-boot-starter-web - org.codehaus.groovy + org.apache.groovy groovy ${groovy.version} @@ -39,6 +40,11 @@ h2 runtime + + io.rest-assured + rest-assured + test + @@ -71,8 +77,8 @@ com.baeldung.springwithgroovy.SpringBootGroovyApplication - 3.0.13 - 1.9.0 + 4.0.11 + 3.0.2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy index 000d981701..31274e1f07 100644 --- a/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy +++ b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy @@ -1,11 +1,11 @@ package com.baeldung.springwithgroovy.entity -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.GeneratedValue -import javax.persistence.GenerationType -import javax.persistence.Id -import javax.persistence.Table +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.Table @Entity @Table(name = 'todo') diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index b0f0c780aa..fd3daa1a79 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -225,7 +225,7 @@ 2.2.4 3.2.0 0.23.0 - 2.1.0 + 5.10.0 1.5-beta1 2.1 2.6.0 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java index 7f3ad7988f..e63726c926 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java @@ -1,9 +1,10 @@ package com.baeldung.caffeine; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; /** * Because the POM imports Spring Security, we need a simple security @@ -11,14 +12,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur */ @Configuration @EnableWebSecurity -public class SecurityConfiguration extends WebSecurityConfigurerAdapter { +public class SecurityConfiguration { - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { http.csrf().disable(); - http.authorizeRequests() + return http.authorizeRequests() .antMatchers("/**") - .permitAll(); + .permitAll().and().build(); } } diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java index cd5f63e962..c03d351c20 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java @@ -1,13 +1,13 @@ package com.baeldung.scheduling.shedlock; -import net.javacrumbs.shedlock.core.SchedulerLock; +import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component class BaeldungTaskScheduler { @Scheduled(cron = "0 0/15 * * * ?") - @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") + @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastFor = "PT5M", lockAtMostFor = "PT14M") public void scheduledTask() { System.out.println("Running ShedLock task"); } diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml index 3477520208..03c24f7778 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: datasource: driverClassName: org.h2.Driver - url: jdbc:h2:mem:shedlock_DB;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + url: jdbc:h2:mem:shedlock_db;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE username: sa password: diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/schema.sql b/spring-boot-modules/spring-boot-libraries/src/main/resources/schema.sql new file mode 100644 index 0000000000..d5a5d51b74 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS shedlock( + name VARCHAR(64) NOT NULL, + lock_until TIMESTAMP NOT NULL, + locked_at TIMESTAMP NOT NULL, + locked_by VARCHAR(255) NOT NULL, + PRIMARY KEY (name) +); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml index 31c0f4bd02..de21a99ab3 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml @@ -40,6 +40,7 @@ org.projectlombok lombok + ${lombok.version} provided diff --git a/spring-boot-modules/spring-boot-mvc-5/README.md b/spring-boot-modules/spring-boot-mvc-5/README.md index 782adb7b34..c72d72c84f 100644 --- a/spring-boot-modules/spring-boot-mvc-5/README.md +++ b/spring-boot-modules/spring-boot-mvc-5/README.md @@ -5,3 +5,4 @@ This module contains articles about Spring Web MVC in Spring Boot projects. ### Relevant Articles: - [Enable and Disable Endpoints at Runtime With Spring Boot](https://www.baeldung.com/spring-boot-enable-disable-endpoints-at-runtime) - [Extracting a Custom Header From the Request](https://www.baeldung.com/spring-extract-custom-header-request) +- [Modify Request Body Before Reaching Controller in Spring Boot](https://www.baeldung.com/spring-boot-change-request-body-before-controller) diff --git a/spring-boot-modules/spring-boot-mvc-5/pom.xml b/spring-boot-modules/spring-boot-mvc-5/pom.xml index a516cab049..10a58a6a59 100644 --- a/spring-boot-modules/spring-boot-mvc-5/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-5/pom.xml @@ -49,6 +49,10 @@ commons-configuration ${commons-configuration.version} + + org.springframework.boot + spring-boot-starter-aop + @@ -61,6 +65,14 @@ JAR + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/ModifyRequestApp.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/ModifyRequestApp.java new file mode 100644 index 0000000000..7dd937d5b8 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/ModifyRequestApp.java @@ -0,0 +1,11 @@ +package com.baeldung.modifyrequest; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.modifyrequest") +public class ModifyRequestApp { + public static void main(String[] args) { + SpringApplication.run(ModifyRequestApp.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java new file mode 100644 index 0000000000..d4533dcf0b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java @@ -0,0 +1,78 @@ +package com.baeldung.modifyrequest.aop; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.core.MethodParameter; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice; + +import java.io.*; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; + +@RestControllerAdvice +@Profile("aspectExample") +public class EscapeHtmlAspect implements RequestBodyAdvice { + + private static final Logger logger = LoggerFactory.getLogger(EscapeHtmlAspect.class); + + @Override + public boolean supports(MethodParameter methodParameter, Type targetType, Class> converterType) { + //Apply this to all Controllers + return true; + } + + @Override + public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, + Class> converterType) throws IOException { + logger.info("beforeBodyRead called"); + InputStream inputStream = inputMessage.getBody(); + return new HttpInputMessage() { + @Override + public InputStream getBody() throws IOException { + return new ByteArrayInputStream(escapeHtml(inputStream).getBytes(StandardCharsets.UTF_8)); + } + + @Override + public HttpHeaders getHeaders() { + return inputMessage.getHeaders(); + } + }; + } + + @Override + public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, + Class> converterType) { + // Return the modified object after reading the body + return body; + } + + @Override + public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, + Class> converterType) { + //return the original body + return body; + } + + private String escapeHtml(InputStream inputStream) throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try (inputStream) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + char[] charBuffer = new char[128]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } + String input = stringBuilder.toString(); + // Escape HTML characters + return input.replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">"); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java new file mode 100644 index 0000000000..2fc1fbc310 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java @@ -0,0 +1,26 @@ +package com.baeldung.modifyrequest.config; + +import com.baeldung.modifyrequest.interceptor.EscapeHtmlRequestInterceptor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@Profile("interceptorExample") +public class WebMvcConfiguration implements WebMvcConfigurer { + private static final Logger logger = LoggerFactory.getLogger(WebMvcConfiguration.class); + + @Override + public void addInterceptors(InterceptorRegistry registry) { + logger.info("addInterceptors() called"); + registry.addInterceptor(new EscapeHtmlRequestInterceptor()) + .addPathPatterns("/save"); + + WebMvcConfigurer.super.addInterceptors(registry); + } +} + diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/controller/UserController.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/controller/UserController.java new file mode 100644 index 0000000000..26450dd70d --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/controller/UserController.java @@ -0,0 +1,23 @@ +package com.baeldung.modifyrequest.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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; + +@RestController +@RequestMapping("/") +public class UserController { + Logger logger = LoggerFactory.getLogger(UserController.class); + + @PostMapping(value = "save") + public ResponseEntity saveUser(@RequestBody String user) { + logger.info("save user info into database"); + ResponseEntity responseEntity = new ResponseEntity<>(user, HttpStatus.CREATED); + return responseEntity; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/filter/EscapeHtmlFilter.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/filter/EscapeHtmlFilter.java new file mode 100644 index 0000000000..45cad3be1c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/filter/EscapeHtmlFilter.java @@ -0,0 +1,27 @@ +package com.baeldung.modifyrequest.filter; + +import com.baeldung.modifyrequest.requestwrapper.EscapeHtmlRequestWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +@Component +@Order(1) +@Profile("filterExample") +public class EscapeHtmlFilter implements Filter { + Logger logger = LoggerFactory.getLogger(EscapeHtmlFilter.class); + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + logger.info("Modify the request"); + + filterChain.doFilter(new EscapeHtmlRequestWrapper((HttpServletRequest) servletRequest), servletResponse); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/interceptor/EscapeHtmlRequestInterceptor.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/interceptor/EscapeHtmlRequestInterceptor.java new file mode 100644 index 0000000000..1ad39605e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/interceptor/EscapeHtmlRequestInterceptor.java @@ -0,0 +1,19 @@ +package com.baeldung.modifyrequest.interceptor; + +import com.baeldung.modifyrequest.requestwrapper.EscapeHtmlRequestWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class EscapeHtmlRequestInterceptor implements HandlerInterceptor { + private static final Logger logger = LoggerFactory.getLogger(EscapeHtmlRequestInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + EscapeHtmlRequestWrapper escapeHtmlRequestWrapper = new EscapeHtmlRequestWrapper(request); + return true; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java new file mode 100644 index 0000000000..e7b3abbc1f --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java @@ -0,0 +1,67 @@ +package com.baeldung.modifyrequest.requestwrapper; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.*; + +public class EscapeHtmlRequestWrapper extends HttpServletRequestWrapper { + private String body = null; + public EscapeHtmlRequestWrapper(HttpServletRequest request) throws IOException { + super(request); + this.body = this.escapeHtml(request); + } + + private String escapeHtml(HttpServletRequest request) throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try (InputStream inputStream = request.getInputStream()) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + char[] charBuffer = new char[128]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } + String input = stringBuilder.toString(); + // Escape HTML characters + return input.replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll("'", "'"); + } + + @Override + public ServletInputStream getInputStream() { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); + ServletInputStream servletInputStream = new ServletInputStream() { + + @Override + public int read() { + return byteArrayInputStream.read(); + } + + @Override + public boolean isFinished() { + return false; + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setReadListener(ReadListener listener) { + + } + }; + return servletInputStream; + } + + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(this.getInputStream())); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/filter-sequence-design.puml b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/filter-sequence-design.puml new file mode 100644 index 0000000000..41689ac723 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/filter-sequence-design.puml @@ -0,0 +1,31 @@ +@startuml +'https://plantuml.com/sequence-diagram +skinparam sequenceMessageAlign direction +skinparam handwritten true +skinparam sequence { +ParticipantBackgroundColor beige +ParticipantPadding 50 +} + +autonumber + +Browser -[#63b175]> Filter: HTTP Request +activate Browser +activate Filter +Filter -[#63b175]> Filter: doFilter() +Filter -[#63b175]> DispatcherServlet: HTTP Request +activate DispatcherServlet + + +DispatcherServlet -[#63b175]> Controller: HTTP Request +activate Controller +Controller --[#63b175]> DispatcherServlet: HTTP Response +deactivate Controller + +DispatcherServlet --[#63b175]> Filter: HTTP Response +deactivate DispatcherServlet + +Filter --[#63b175]> Browser: HTTP Response +deactivate Filter +deactivate Browser +@enduml \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/interceptor-sequence-design.puml b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/interceptor-sequence-design.puml new file mode 100644 index 0000000000..429b8182ca --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/interceptor-sequence-design.puml @@ -0,0 +1,33 @@ +@startuml +'https://plantuml.com/sequence-diagram +skinparam sequenceMessageAlign direction +skinparam handwritten true +skinparam sequence { +ParticipantBackgroundColor beige +ParticipantPadding 50 +} + +autonumber + +Browser -[#63b175]> Filter: Http Request +activate Browser +activate Filter +Filter -[#63b175]> DispatcherServlet: Http Request +activate DispatcherServlet + +DispatcherServlet -[#63b175]> Interceptor: Http Request +activate Interceptor +Interceptor -[#63b175]> Interceptor: preHandle() +Interceptor -[#63b175]> Controller: Http Request +activate Controller +Controller --[#63b175]> Interceptor: Http Response +deactivate Controller +Interceptor --[#63b175]> DispatcherServlet: Http Response +deactivate Interceptor +DispatcherServlet --[#63b175]> Filter: Http Response +deactivate DispatcherServlet + +Filter --[#63b175]> Browser: Http Response +deactivate Filter +deactivate Browser +@enduml \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java new file mode 100644 index 0000000000..ef18591ccb --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java @@ -0,0 +1,54 @@ +package com.baeldung.modifyrequest; + +import com.baeldung.modifyrequest.controller.UserController; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.net.URI; +import java.util.Map; + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@WebMvcTest(UserController.class) +@ActiveProfiles("aspectExample") +public class EscapeHtmlAspectIntegrationTest { + Logger logger = LoggerFactory.getLogger(EscapeHtmlAspectIntegrationTest.class); + + @Autowired + private MockMvc mockMvc; + @Test + void givenAspect_whenEscapeHtmlAspect_thenEscapeHtml() throws Exception { + + Map requestBody = Map.of( + "name", "James Cameron", + "email", "james@gmail.com" + ); + + Map expectedResponseBody = Map.of( + "name", "James Cameron", + "email", "<script>alert()</script>james@gmail.com" + ); + + ObjectMapper objectMapper = new ObjectMapper(); + + mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status() + .isCreated()) + .andExpect(MockMvcResultMatchers.content() + .json(objectMapper.writeValueAsString(expectedResponseBody))); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java new file mode 100644 index 0000000000..c813827422 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.modifyrequest; + +import com.baeldung.modifyrequest.controller.UserController; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.net.URI; +import java.util.Map; + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@WebMvcTest(UserController.class) +@ActiveProfiles("filterExample") +public class EscapeHtmlFilterIntegrationTest { + Logger logger = LoggerFactory.getLogger(EscapeHtmlFilterIntegrationTest.class); + + @Autowired + private MockMvc mockMvc; + @Test + void givenFilter_whenEscapeHtmlFilter_thenEscapeHtml() throws Exception { + Map requestBody = Map.of( + "name", "James Cameron", + "email", "james@gmail.com" + ); + + Map expectedResponseBody = Map.of( + "name", "James Cameron", + "email", "<script>alert()</script>james@gmail.com" + ); + + ObjectMapper objectMapper = new ObjectMapper(); + + mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))).andExpect(MockMvcResultMatchers.status() + .isCreated()).andExpect(MockMvcResultMatchers.content() + .json(objectMapper.writeValueAsString(expectedResponseBody))); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java new file mode 100644 index 0000000000..9afc7f7e5a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.modifyrequest; + +import com.baeldung.modifyrequest.controller.UserController; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.net.URI; +import java.util.Map; + + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@WebMvcTest(UserController.class) +@ActiveProfiles("interceptorExample") +public class EscapeHtmlInterceptorIntegrationTest { + Logger logger = LoggerFactory.getLogger(EscapeHtmlInterceptorIntegrationTest.class); + + @Autowired + private MockMvc mockMvc; + + @Test + void givenInterceptor_whenEscapeHtmlInterceptor_thenEscapeHtml() throws Exception { + Map requestBody = Map.of( + "name", "James Cameron", + "email", "james@gmail.com" + ); + + ObjectMapper objectMapper = new ObjectMapper(); + mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))).andExpect(MockMvcResultMatchers.status() + .is4xxClientError()); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-birt/pom.xml b/spring-boot-modules/spring-boot-mvc-birt/pom.xml index cc4b7f8283..b2cda67974 100644 --- a/spring-boot-modules/spring-boot-mvc-birt/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-birt/pom.xml @@ -48,6 +48,7 @@ org.projectlombok lombok + ${lombok.version} provided diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 963cda61b9..ab1c867d66 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -92,6 +92,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/spring-boot-modules/spring-boot-redis/pom.xml b/spring-boot-modules/spring-boot-redis/pom.xml index fa6b5a59c1..57a894e2fc 100644 --- a/spring-boot-modules/spring-boot-redis/pom.xml +++ b/spring-boot-modules/spring-boot-redis/pom.xml @@ -73,7 +73,6 @@ - 15 6.0.3 0.7.3 diff --git a/spring-boot-modules/spring-boot-resilience4j/pom.xml b/spring-boot-modules/spring-boot-resilience4j/pom.xml index 355ef8f92d..2f3af8f9d2 100644 --- a/spring-boot-modules/spring-boot-resilience4j/pom.xml +++ b/spring-boot-modules/spring-boot-resilience4j/pom.xml @@ -53,7 +53,7 @@ 2.35.0 2.0.2 - 2.15.2 + 2.16.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java index 45cc1ebb33..6870f4e6bb 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java @@ -1,14 +1,16 @@ package com.baeldung.spring.boot.management.logging; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; @Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf() - .ignoringAntMatchers("/actuator/**"); +public class SecurityConfig { + @Bean + public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { + return http.csrf() + .ignoringAntMatchers("/actuator/**").and() + .build(); } } diff --git a/spring-boot-modules/spring-boot-telegram/pom.xml b/spring-boot-modules/spring-boot-telegram/pom.xml index 9077e90400..a26566819a 100644 --- a/spring-boot-modules/spring-boot-telegram/pom.xml +++ b/spring-boot-modules/spring-boot-telegram/pom.xml @@ -39,7 +39,6 @@ - 17 6.7.0 diff --git a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml index 600fedc774..371b5c2976 100644 --- a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml @@ -44,7 +44,6 @@ 1.11.407 5.0.3 0.7.6 - 1.18.26 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml index 2871f129b5..1ef57d4be3 100644 --- a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml @@ -34,8 +34,4 @@ - - 1.18.26 - - \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-aws/pom.xml b/spring-cloud-modules/spring-cloud-aws/pom.xml index ff376b02cb..3de0c7146a 100644 --- a/spring-cloud-modules/spring-cloud-aws/pom.xml +++ b/spring-cloud-modules/spring-cloud-aws/pom.xml @@ -69,8 +69,8 @@ postgresql - mysql - mysql-connector-java + com.mysql + mysql-connector-j diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml index 08a85d191a..e540645f30 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml @@ -74,6 +74,7 @@ org.projectlombok lombok + ${lombok.version} org.testcontainers diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java index af60c3849b..6efacc03b1 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java @@ -1,19 +1,23 @@ package com.baeldung.cloud.openfeign.oauthfeign; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; @Configuration -public class OAuth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { +public class OAuth2WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf() .disable() .oauth2Client(); + http .authorizeRequests().anyRequest().permitAll(); + + return http.build(); } } diff --git a/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml index 7dbbb27a77..53bc37212c 100644 --- a/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -23,8 +23,8 @@ spring-boot-starter-data-jpa - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.springframework.cloud diff --git a/spring-cloud-modules/spring-cloud-vault/pom.xml b/spring-cloud-modules/spring-cloud-vault/pom.xml index e4cf020986..1698b1f357 100644 --- a/spring-cloud-modules/spring-cloud-vault/pom.xml +++ b/spring-cloud-modules/spring-cloud-vault/pom.xml @@ -42,8 +42,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.springframework.boot diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index f27b16acc3..d22178004c 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -119,20 +119,10 @@ spring-boot-starter-test test - - - net.javacrumbs.shedlock - shedlock-spring - ${shedlock.version} - - - net.javacrumbs.shedlock - shedlock-provider-jdbc-template - ${shedlock.version} - org.projectlombok lombok + ${lombok.version} @@ -161,7 +151,6 @@ 1.3.2 3.6 - 2.1.0 3.22.0-GA 3.2.2 diff --git a/spring-credhub/pom.xml b/spring-credhub/pom.xml index defe378b6b..f257d549bf 100644 --- a/spring-credhub/pom.xml +++ b/spring-credhub/pom.xml @@ -23,6 +23,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.credhub diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index 042e81971f..0b0e38a2be 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -53,16 +53,17 @@ - org.apache.commons + commons-io commons-io ${commons-io.version} + + com.baeldung.SpringDemoApplication 7.14.0 - 1.3.2 - 5.10.0 + 5.10.1 \ No newline at end of file diff --git a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java index 637dbdb540..70a917d999 100644 --- a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java +++ b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java @@ -3,6 +3,7 @@ package com.baeldung.cucumberoptions; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -11,12 +12,12 @@ import org.springframework.web.bind.annotation.RestController; public class HealthCheckController { @GetMapping(path = "/v1/status", produces = APPLICATION_JSON_VALUE) - public HttpStatus getV1Status() { + public HttpStatusCode getV1Status() { return ResponseEntity.ok().build().getStatusCode(); } @GetMapping(path = "/v2/status", produces = APPLICATION_JSON_VALUE) - public HttpStatus getV2Status() { + public HttpStatusCode getV2Status() { return ResponseEntity.ok().build().getStatusCode(); } } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java index 7b5c4e21ff..f243c68237 100644 --- a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java @@ -9,6 +9,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.web.client.ResponseErrorHandler; @@ -69,7 +71,7 @@ public class SpringIntegrationTest { @Override public boolean hasError(ClientHttpResponse response) throws IOException { - hadError = response.getRawStatusCode() >= 400; + hadError = response.getStatusCode().value() >= 400; return hadError; } diff --git a/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java index 9611e95dcf..e4e0b2a883 100644 --- a/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java @@ -5,6 +5,7 @@ import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -29,7 +30,7 @@ public class StepDefsIntegrationTest extends SpringIntegrationTest { @Then("^the client receives status code of (\\d+)$") public void the_client_receives_status_code_of(int statusCode) throws Throwable { - final HttpStatus currentStatusCode = latestResponse.getTheResponse().getStatusCode(); + final HttpStatusCode currentStatusCode = latestResponse.getTheResponse().getStatusCode(); assertThat("status code is incorrect : " + latestResponse.getBody(), currentStatusCode.value(), is(statusCode)); } diff --git a/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java index 999adadbef..7304f269e7 100644 --- a/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java @@ -3,7 +3,8 @@ package com.baeldung.cucumberoptions; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; -import org.springframework.http.HttpStatus; + +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; @@ -32,7 +33,7 @@ public class HealthCheckStepDefsIntegrationTest extends SpringIntegrationTest { @Then("^the client receives (\\d+) status code$") public void verifyStatusCode(int statusCode) throws Throwable { - final HttpStatus currentStatusCode = statusResponse.getStatusCode(); + final HttpStatusCode currentStatusCode = statusResponse.getStatusCode(); assertThat(currentStatusCode.value(), is(statusCode)); } } \ No newline at end of file diff --git a/spring-di-2/pom.xml b/spring-di-2/pom.xml index 0bd6c41a8c..898dd182f1 100644 --- a/spring-di-2/pom.xml +++ b/spring-di-2/pom.xml @@ -55,9 +55,9 @@ - org.codehaus.mojo + dev.aspectj aspectj-maven-plugin - ${aspectj-plugin.version} + ${aspectj-maven-plugin.version} ${java.version} @@ -80,7 +80,7 @@ 3.1.2 - 1.14.0 + 1.13.1 2.17.1 diff --git a/spring-di-4/README.md b/spring-di-4/README.md index 8e73aff437..bed8b5a78d 100644 --- a/spring-di-4/README.md +++ b/spring-di-4/README.md @@ -7,4 +7,5 @@ This module contains articles about dependency injection with Spring - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) - [Spring @Component Annotation](https://www.baeldung.com/spring-component-annotation) - [Why Is Field Injection Not Recommended?](https://www.baeldung.com/java-spring-field-injection-cons) +- [Setting a Spring Bean to Null](https://www.baeldung.com/spring-setting-bean-null) - More articles: [[<-- prev]](../spring-di-3) diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index e0071a4206..02a531fe18 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -60,8 +60,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} runtime @@ -162,7 +162,7 @@ 3.21.0-GA 5.2.5.Final - 5.1.40 + 8.2.0 7.0.73 10.13.1.1 diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index abf5cfb3d6..315f549c12 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -17,7 +17,6 @@ - org.springframework.integration spring-integration-core @@ -29,11 +28,6 @@ ${javax-activation.version} true - - javax.mail - mail - ${javax-mail.version} - org.springframework.integration spring-integration-twitter @@ -85,16 +79,21 @@ h2 ${h2.version} - - javax.xml.bind - jaxb-api - ${jaxb-api.version} - org.postgresql postgresql ${postgresql.version} + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.sun.mail + jakarta.mail + ${jakarta.mail.version} + @@ -124,14 +123,13 @@ - 5.1.13.RELEASE + 6.0.0 1.1.4.RELEASE 5.0.13.RELEASE - 1.4.7 1.1.1 2.10 - 2.3.0 42.3.8 + 2.0.1 \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java index adaeac5386..8afd39e9ab 100644 --- a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java +++ b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java @@ -1,6 +1,7 @@ package com.baeldung.dsl; import java.io.File; +import java.time.Duration; import java.util.Scanner; import java.util.concurrent.TimeUnit; @@ -14,7 +15,6 @@ import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.core.GenericSelector; import org.springframework.integration.core.MessageSource; import org.springframework.integration.dsl.IntegrationFlow; -import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; import org.springframework.integration.dsl.MessageChannels; import org.springframework.integration.file.FileReadingMessageSource; @@ -69,7 +69,7 @@ public class JavaDSLFileCopyConfig { @Bean public IntegrationFlow fileMover() { - return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) .filter(onlyJpgs()) .handle(targetDirectory()) .get(); @@ -77,7 +77,7 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileMoverWithLambda() { - return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) .filter(message -> ((File) message).getName() .endsWith(".jpg")) .handle(targetDirectory()) @@ -92,7 +92,7 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileMoverWithPriorityChannel() { - return IntegrationFlows.from(sourceDirectory()) + return IntegrationFlow.from(sourceDirectory()) .filter(onlyJpgs()) .channel("alphabetically") .handle(targetDirectory()) @@ -113,7 +113,7 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileReader() { - return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) + return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) .filter(onlyJpgs()) .channel("holdingTank") .get(); @@ -121,16 +121,16 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileWriter() { - return IntegrationFlows.from("holdingTank") - .bridge(e -> e.poller(Pollers.fixedRate(1, TimeUnit.SECONDS, 20))) + return IntegrationFlow.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit())))) .handle(targetDirectory()) .get(); } // @Bean public IntegrationFlow anotherFileWriter() { - return IntegrationFlows.from("holdingTank") - .bridge(e -> e.poller(Pollers.fixedRate(2, TimeUnit.SECONDS, 10))) + return IntegrationFlow.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit())))) .handle(anotherTargetDirectory()) .get(); } diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 14ac366e74..c1dee7fa9f 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -35,6 +35,11 @@ org.springframework spring-orm + + org.hibernate.orm + hibernate-core + ${hibernate-core.version} + org.springframework.boot @@ -58,7 +63,8 @@ - 1.8.29 + 2.0.1 + 6.4.0.Final \ No newline at end of file diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java index 6d921045b7..01e16cf0f7 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java @@ -1,6 +1,6 @@ package com.baeldung.spring.jinq.config; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; import org.jinq.jpa.JinqJPAStreamProvider; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java index 263e6c7622..a0b9620629 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java @@ -1,19 +1,23 @@ package com.baeldung.spring.jinq.entities; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + + @Entity(name = "CAR") public class Car { + @Id private String model; private String description; private int year; private String engine; + @ManyToOne + @JoinColumn(name = "name") private Manufacturer manufacturer; - @Id public String getModel() { return model; } @@ -46,8 +50,6 @@ public class Car { this.engine = engine; } - @OneToOne - @JoinColumn(name = "name") public Manufacturer getManufacturer() { return manufacturer; } diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java index f6e5fd23de..0021e45658 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java @@ -2,18 +2,19 @@ package com.baeldung.spring.jinq.entities; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; @Entity(name = "MANUFACTURER") public class Manufacturer { + @Id private String name; private String city; + @OneToMany(mappedBy = "model") private List cars; - @Id public String getName() { return name; } @@ -30,7 +31,6 @@ public class Manufacturer { this.city = city; } - @OneToMany(mappedBy = "model") public List getCars() { return cars; } @@ -38,5 +38,4 @@ public class Manufacturer { public void setCars(List cars) { this.cars = cars; } - } diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java index 42b81ecc59..e85231f537 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java @@ -1,7 +1,7 @@ package com.baeldung.spring.jinq.repositories; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; import org.jinq.jpa.JPAJinqStream; import org.jinq.jpa.JinqJPAStreamProvider; diff --git a/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java b/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java index 1a486d1003..7c65a831c4 100644 --- a/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java @@ -4,7 +4,6 @@ import com.baeldung.spring.jinq.JinqApplication; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import com.baeldung.spring.jinq.JinqApplication; @SpringBootTest(classes = JinqApplication.class) public class SpringContextTest { diff --git a/spring-kafka-2/README.md b/spring-kafka-2/README.md index 43b2f59147..250927314c 100644 --- a/spring-kafka-2/README.md +++ b/spring-kafka-2/README.md @@ -9,3 +9,4 @@ This module contains articles about Spring with Kafka - [Understanding Kafka Topics and Partitions](https://www.baeldung.com/kafka-topics-partitions) - [How to Subscribe a Kafka Consumer to Multiple Topics](https://www.baeldung.com/kafka-subscribe-consumer-multiple-topics) - [Splitting Streams in Kafka](https://www.baeldung.com/kafka-splitting-streams) +- [Manage Kafka Consumer Groups](https://www.baeldung.com/kafka-manage-consumer-groups) diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index fdf7da7438..7a4d5a5fea 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -38,6 +38,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.kafka @@ -64,7 +65,7 @@ - 1.16.2 + 1.19.3 3.0.12 3.6.0 1.16.2 diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java index 1620add9ca..ddbb105a67 100644 --- a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java @@ -14,7 +14,7 @@ import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(classes = ManagingConsumerGroupsApplicationKafkaApp.class) -@EmbeddedKafka(partitions = 2, brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092"}) +@EmbeddedKafka(partitions = 2, brokerProperties = {"listeners=PLAINTEXT://localhost:9098", "port=9098"}) public class ManagingConsumerGroupsIntegrationTest { private static final String CONSUMER_1_IDENTIFIER = "org.springframework.kafka.KafkaListenerEndpointContainer#1"; diff --git a/spring-kafka-3/pom.xml b/spring-kafka-3/pom.xml new file mode 100644 index 0000000000..972412d18e --- /dev/null +++ b/spring-kafka-3/pom.xml @@ -0,0 +1,36 @@ + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + 4.0.0 + + spring-kafka-3 + jar + + spring-kafka-3 + + + + org.springframework.kafka + spring-kafka + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.kafka + spring-kafka-test + test + + + + + 3.0.12 + + diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/SomeData.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/SomeData.java new file mode 100644 index 0000000000..eb2e57c33d --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/SomeData.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.kafka; + +import java.time.Instant; + +public class SomeData { + + private String id; + private String type; + private String status; + private Instant timestamp; + + public SomeData() { + } + + public SomeData(String id, String type, String status, Instant timestamp) { + this.id = id; + this.type = type; + this.status = status; + this.timestamp = timestamp; + } + + public String getId() { + return id; + } + + public String getType() { + return type; + } + + public String getStatus() { + return status; + } + + public Instant getTimestamp() { + return timestamp; + } +} diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ListenerConfiguration.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ListenerConfiguration.java new file mode 100644 index 0000000000..e35b1ee415 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ListenerConfiguration.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.kafka; + +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +@Configuration +public class ListenerConfiguration { + + @Bean("messageListenerContainer") + public ConcurrentKafkaListenerContainerFactory messageListenerContainer() { + ConcurrentKafkaListenerContainerFactory container = new ConcurrentKafkaListenerContainerFactory<>(); + container.setConsumerFactory(someDataConsumerFactory()); + return container; + } + + @Bean + public ConsumerFactory someDataConsumerFactory() { + JsonDeserializer payloadJsonDeserializer = new JsonDeserializer<>(); + payloadJsonDeserializer.trustedPackages("com.baeldung.spring.kafka"); + return new DefaultKafkaConsumerFactory<>( + consumerConfigs(), + new StringDeserializer(), + payloadJsonDeserializer + ); + } + + @Bean + public Map consumerConfigs() { + return Map.of( + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "PLAINTEXT://localhost:9092", + ConsumerConfig.GROUP_ID_CONFIG, "some-group-id" + ); + } +} \ No newline at end of file diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ProducerConfiguration.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ProducerConfiguration.java new file mode 100644 index 0000000000..7373424841 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ProducerConfiguration.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.kafka; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.serializer.JsonSerializer; +import org.springframework.kafka.support.serializer.StringOrBytesSerializer; + +import java.time.Instant; +import java.util.Map; + +@Configuration +public class ProducerConfiguration { + + @Bean + public KafkaTemplate kafkaTemplate() { + return new KafkaTemplate<>(producerFactory()); + } + + @Bean + public ProducerFactory producerFactory() { + JsonSerializer jsonSerializer = new JsonSerializer<>(); + jsonSerializer.setAddTypeInfo(true); + return new DefaultKafkaProducerFactory<>( + producerFactoryConfig(), + new StringOrBytesSerializer(), + jsonSerializer + ); + } + + @Bean + public Map producerFactoryConfig() { + return Map.of( + ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "PLAINTEXT://localhost:9092" + ); + } +} \ No newline at end of file diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/TrustedPackagesLiveTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/TrustedPackagesLiveTest.java new file mode 100644 index 0000000000..fa4b79cd65 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/TrustedPackagesLiveTest.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.kafka; + +import java.time.Instant; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.apache.kafka.clients.producer.ProducerRecord; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +/** + * This test requires a running instance of kafka to be present + */ +@SpringBootTest +public class TrustedPackagesLiveTest { + + @Autowired + private KafkaTemplate kafkaTemplate; + + @SpyBean + TestConsumer testConsumer; + + @Test + void givenMessageInTheTopic_whenTypeInfoPackageIsTrusted_thenMessageIsSuccessfullyConsumed() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + + Mockito.doAnswer(invocationOnMock -> { + try { + latch.countDown(); + return invocationOnMock.callRealMethod(); + } catch (Exception e) { + return null; + } + }).when(testConsumer).onMessage(Mockito.any()); + + SomeData someData = new SomeData("1", "active", "sent", Instant.now()); + kafkaTemplate.send(new ProducerRecord<>("sourceTopic", null, someData)); + + Assertions.assertTrue(latch.await(20L, TimeUnit.SECONDS)); + } + + @Component + static class TestConsumer { + + @KafkaListener(topics = "sourceTopic", containerFactory = "messageListenerContainer") + public void onMessage(SomeData someData) { + + } + } +} diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 7ff7a9710a..6428734de2 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -48,6 +48,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.kafka @@ -92,7 +93,7 @@ 3.0.5 1.10.5 - 1.16.2 + 1.19.3 \ No newline at end of file diff --git a/spring-native/pom-nativeimage.xml b/spring-native/pom-nativeimage.xml index 6d42bedbe1..4fc01e4574 100644 --- a/spring-native/pom-nativeimage.xml +++ b/spring-native/pom-nativeimage.xml @@ -114,9 +114,6 @@ 2.7.1 0.12.1 0.9.17 - 1.8 - 1.8 - 1.8 diff --git a/spring-pulsar/pom.xml b/spring-pulsar/pom.xml index a1c834f830..b2feaddfb1 100644 --- a/spring-pulsar/pom.xml +++ b/spring-pulsar/pom.xml @@ -43,7 +43,6 @@ - 17 0.2.0 diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index e8919bfadb..ddae53f64f 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index ccf9fca8c1..37bd82ef3b 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -6,7 +6,7 @@ import static org.quartz.TriggerBuilder.newTrigger; import java.io.IOException; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.*; diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java index f824765efe..c113482c76 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java @@ -1,6 +1,6 @@ package org.baeldung.springquartz.basics.scheduler; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import javax.sql.DataSource; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; diff --git a/spring-reactive-modules/spring-reactive-2/pom.xml b/spring-reactive-modules/spring-reactive-2/pom.xml index 90c5300cc8..fac93154c8 100644 --- a/spring-reactive-modules/spring-reactive-2/pom.xml +++ b/spring-reactive-modules/spring-reactive-2/pom.xml @@ -10,9 +10,10 @@ spring sample project about new features - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -37,6 +38,7 @@ org.projectlombok lombok provided + ${lombok.version} org.springframework.boot @@ -44,8 +46,8 @@ test - com.github.tomakehurst - wiremock-jre8 + org.wiremock + wiremock ${wiremock.version} test @@ -63,6 +65,11 @@ org.springframework.boot spring-boot-starter-tomcat + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + @@ -115,7 +122,7 @@ 1.0.1.RELEASE - 2.24.0 + 3.3.1 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring6ReactiveApplication.java similarity index 77% rename from spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring6ReactiveApplication.java index ef862dd957..f716af4a0e 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring6ReactiveApplication.java @@ -5,10 +5,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; @SpringBootApplication(exclude = { RedisAutoConfiguration.class }) -public class Spring5ReactiveApplication{ +public class Spring6ReactiveApplication { public static void main(String[] args) { - SpringApplication.run(Spring5ReactiveApplication.class, args); + SpringApplication.run(Spring6ReactiveApplication.class, args); } } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java index d8edaf7fd5..bec7dd2e0c 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -22,9 +22,10 @@ public class ConsumerSSEApplication { @Bean public SecurityWebFilterChain sseConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .permitAll(); + http.authorizeExchange(auth -> auth + .anyExchange().permitAll() + ) + .csrf(ServerHttpSecurity.CsrfSpec::disable); return http.build(); } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java index 7b1fb06459..1652e2f25d 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java @@ -34,7 +34,7 @@ public class FormHandler { private AtomicLong extractData(List dataBuffers) { AtomicLong atomicLong = new AtomicLong(0); - dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() + dataBuffers.forEach(d -> atomicLong.addAndGet(d.toByteBuffer() .array().length)); return atomicLong; } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java index 8d16434920..20cc162cde 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java @@ -9,7 +9,7 @@ public class CpuUtils { private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); static Double getUsage() { - return (operatingSystemMXBean.getSystemCpuLoad() / operatingSystemMXBean.getAvailableProcessors()) * 100; + return (operatingSystemMXBean.getCpuLoad() / operatingSystemMXBean.getAvailableProcessors()) * 100; } } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java index 1fbb9958e7..456eec8f84 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java @@ -23,7 +23,7 @@ public class StaticContentConfig { GET("/"), request -> ok() .contentType(MediaType.TEXT_HTML) - .syncBody(html) + .bodyValue(html) ); } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java index 4cbb65dc60..bcbd4d55d7 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java @@ -15,10 +15,11 @@ public class FunctionalValidationsApplication { @Bean public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .permitAll(); - http.csrf().disable(); + http.authorizeExchange(auth -> auth + .anyExchange().permitAll() + ) + .csrf(ServerHttpSecurity.CsrfSpec::disable); + return http.build(); } } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java index 992f07481c..6ca6c369c1 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java @@ -1,7 +1,7 @@ package com.baeldung.validations.functional.model; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java index a12d762fe5..c087e10b3f 100644 --- a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java +++ b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java @@ -24,49 +24,45 @@ public class BackpressureUnitTest { ); StepVerifier.create(limit) - .expectSubscription() - .thenRequest(15) - .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - .expectNext(11, 12, 13, 14, 15) - .thenRequest(10) - .expectNext(16, 17, 18, 19, 20, 21, 22, 23, 24, 25) - .verifyComplete(); + .expectSubscription() + .thenRequest(15) + .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .expectNext(11, 12, 13, 14, 15) + .thenRequest(10) + .expectNext(16, 17, 18, 19, 20, 21, 22, 23, 24, 25) + .verifyComplete(); } @Test public void whenRequestingChunks10_thenMessagesAreReceived() { Flux request = Flux.range(1, 50); - request.subscribe( - integer -> LOGGER.debug(String.valueOf(integer)), - err -> err.printStackTrace(), - () -> LOGGER.debug("All 50 items have been successfully processed!!!"), - subscription -> { - for (int i = 0; i < 5; i++) { - LOGGER.debug("Requesting the next 10 elements!!!"); - subscription.request(10); - } - } - ); + request.subscribe(integer -> LOGGER.debug(String.valueOf(integer)), err -> err.printStackTrace(), () -> LOGGER.debug("All 50 items have been successfully processed!!!"), subscription -> { + for (int i = 0; i < 5; i++) { + LOGGER.debug("Requesting the next 10 elements!!!"); + subscription.request(10); + } + }); StepVerifier.create(request) - .expectSubscription() - .thenRequest(10) - .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - .thenRequest(10) - .expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20) - .thenRequest(10) - .expectNext(21, 22, 23, 24, 25, 26, 27 , 28, 29 ,30) - .thenRequest(10) - .expectNext(31, 32, 33, 34, 35, 36, 37 , 38, 39 ,40) - .thenRequest(10) - .expectNext(41, 42, 43, 44, 45, 46, 47 , 48, 49 ,50) - .verifyComplete(); + .expectSubscription() + .thenRequest(10) + .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .thenRequest(10) + .expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20) + .thenRequest(10) + .expectNext(21, 22, 23, 24, 25, 26, 27, 28, 29, 30) + .thenRequest(10) + .expectNext(31, 32, 33, 34, 35, 36, 37, 38, 39, 40) + .thenRequest(10) + .expectNext(41, 42, 43, 44, 45, 46, 47, 48, 49, 50) + .verifyComplete(); } @Test public void whenCancel_thenSubscriptionFinished() { - Flux cancel = Flux.range(1, 10).log(); + Flux cancel = Flux.range(1, 10) + .log(); cancel.subscribe(new BaseSubscriber() { @Override @@ -78,9 +74,9 @@ public class BackpressureUnitTest { }); StepVerifier.create(cancel) - .expectNext(1, 2, 3) - .thenCancel() - .verify(); + .expectNext(1, 2, 3) + .thenCancel() + .verify(); } } diff --git a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java index 0b4607b54a..4069888dcd 100644 --- a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -8,11 +8,11 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; -import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.Spring6ReactiveApplication; import com.baeldung.reactive.controller.PathPatternController; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5ReactiveApplication.class) +@SpringBootTest(classes = Spring6ReactiveApplication.class) @WithMockUser public class PathPatternsUsingHandlerMethodIntegrationTest { diff --git a/spring-reactive-modules/spring-reactive-3/pom.xml b/spring-reactive-modules/spring-reactive-3/pom.xml index bf2cdbbf2d..17c9690157 100644 --- a/spring-reactive-modules/spring-reactive-3/pom.xml +++ b/spring-reactive-modules/spring-reactive-3/pom.xml @@ -46,6 +46,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.boot diff --git a/spring-reactive-modules/spring-reactive-client/pom.xml b/spring-reactive-modules/spring-reactive-client/pom.xml index 5736ce497f..fe53584cc9 100644 --- a/spring-reactive-modules/spring-reactive-client/pom.xml +++ b/spring-reactive-modules/spring-reactive-client/pom.xml @@ -106,6 +106,7 @@ org.projectlombok lombok + ${lombok.version} org.mockito diff --git a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml index 2ac8ad19ac..e0b21087fa 100644 --- a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml @@ -140,7 +140,6 @@ 2.2.6.RELEASE 2.17.1 - 1.18.26 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data/pom.xml b/spring-reactive-modules/spring-reactive-data/pom.xml index a598315d5d..576a1d9f86 100644 --- a/spring-reactive-modules/spring-reactive-data/pom.xml +++ b/spring-reactive-modules/spring-reactive-data/pom.xml @@ -53,6 +53,7 @@ org.projectlombok lombok true + ${lombok.version} io.projectreactor diff --git a/spring-reactive-modules/spring-reactive-security/pom.xml b/spring-reactive-modules/spring-reactive-security/pom.xml index cf34b21083..25b9f4c38f 100644 --- a/spring-reactive-modules/spring-reactive-security/pom.xml +++ b/spring-reactive-modules/spring-reactive-security/pom.xml @@ -41,6 +41,7 @@ org.projectlombok lombok compile + ${lombok.version} org.apache.geronimo.specs diff --git a/spring-scheduling/README.md b/spring-scheduling/README.md index 4ee306c0e0..4c42c60c37 100644 --- a/spring-scheduling/README.md +++ b/spring-scheduling/README.md @@ -5,3 +5,4 @@ - [How To Do @Async in Spring](https://www.baeldung.com/spring-async) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) - [Remote Debugging with IntelliJ IDEA](https://www.baeldung.com/intellij-remote-debugging) +- [Setup Asynchronous Retry Mechanism in Spring](https://www.baeldung.com/spring-async-retry) diff --git a/spring-security-modules/spring-security-azuread/pom.xml b/spring-security-modules/spring-security-azuread/pom.xml index 7e67a7e635..b32a1eb16a 100644 --- a/spring-security-modules/spring-security-azuread/pom.xml +++ b/spring-security-modules/spring-security-azuread/pom.xml @@ -11,10 +11,6 @@ spring-security-azuread - - 1.8 - - org.springframework.boot @@ -48,6 +44,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java index d6361255e5..414f782907 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java @@ -1,16 +1,17 @@ package com.baeldung.httpsecurityvswebsecurity; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity -public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { +public class HttpSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // Given: HttpSecurity configured http.authorizeRequests() @@ -27,5 +28,6 @@ public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { // When: Accessing specific URLs // Then: Access is granted based on defined rules + return http.build(); } } diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/SecurityConfiguration.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/SecurityConfiguration.java new file mode 100644 index 0000000000..5c0853e6f3 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/SecurityConfiguration.java @@ -0,0 +1,78 @@ +package com.baeldung.httpsecurityvswebsecurity; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.firewall.HttpFirewall; +import org.springframework.security.web.firewall.StrictHttpFirewall; + +import java.util.ArrayList; +import java.util.List; + +import static org.springframework.security.config.Customizer.withDefaults; + +@Configuration +@EnableWebSecurity +public class SecurityConfiguration { + + @Bean + public HttpFirewall allowHttpMethod() { + List allowedMethods = new ArrayList(); + allowedMethods.add("GET"); + allowedMethods.add("POST"); + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowedHttpMethods(allowedMethods); + return firewall; + } + + @Bean + public WebSecurityCustomizer fireWall() { + return (web) -> web.httpFirewall(allowHttpMethod()); + } + + @Bean + public WebSecurityCustomizer ignoringCustomizer() { + return (web) -> web.ignoring().antMatchers("/resources/**", "/static/**"); + } + + @Bean + public WebSecurityCustomizer debugSecurity() { + return (web) -> web.debug(true); + } + + @Bean + public InMemoryUserDetailsManager userDetailsService() { + UserDetails user = User.withUsername("user") + .password(encoder().encode("userPass")) + .roles("ADMIN") + .build(); + return new InMemoryUserDetailsManager(user); + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.authorizeHttpRequests((authorize) -> authorize.antMatchers("/admin/**") + .hasRole("ADMIN") + .anyRequest() + .permitAll()) + .httpBasic(withDefaults()) + .formLogin(withDefaults()) + .csrf(AbstractHttpConfigurer::disable); + return http.build(); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java index 46a82918aa..ec50069ba5 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -1,35 +1,48 @@ package com.baeldung.httpsecurityvswebsecurity; +import org.springframework.context.annotation.Bean; +import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Autowired private UserDetailsService userDetailsService; - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth - .userDetailsService(userDetailsService) - .passwordEncoder(new BCryptPasswordEncoder()); + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); } - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); + authenticationManagerBuilder.userDetailsService(userDetailsService); + AuthenticationManager authenticationManager = authenticationManagerBuilder.build(); + http.authorizeRequests() - .antMatchers("/") - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin(); + .antMatchers("/") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin().and() + .authenticationManager(authenticationManager) + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + + return http.build(); + } + + protected void configure(HttpSecurity http) throws Exception { + } } diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/controller/AdminController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/controller/AdminController.java new file mode 100644 index 0000000000..cd1daee17e --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/controller/AdminController.java @@ -0,0 +1,15 @@ +package com.baeldung.httpsecurityvswebsecurity.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/admin") +public class AdminController { + + @RequestMapping("/greeting") + public String hello() { + return "Hello Admin"; + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml index 3d5ff0cb69..a5ce06f4d9 100644 --- a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml @@ -12,9 +12,7 @@ reactive-resource-server reactive-resource-server Demo project for Spring Boot reactive resource-server - - 17 - + org.springframework.boot diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml index eb507fc3d3..44403cf341 100644 --- a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml @@ -12,9 +12,7 @@ servlet-resource-server servlet-resource-server Demo project for Spring Boot servlet resource-server - - 17 - + org.springframework.boot diff --git a/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java b/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java index 1fb9a6773a..3a8e037f72 100644 --- a/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java +++ b/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java @@ -8,7 +8,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter; diff --git a/spring-security-modules/spring-security-opa/pom.xml b/spring-security-modules/spring-security-opa/pom.xml index a6240f6e69..81c4709124 100644 --- a/spring-security-modules/spring-security-opa/pom.xml +++ b/spring-security-modules/spring-security-opa/pom.xml @@ -23,6 +23,7 @@ org.projectlombok lombok + ${lombok.version} com.google.guava diff --git a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java index 297c391823..956233dfaf 100644 --- a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java @@ -10,11 +10,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.saml.*; import org.springframework.security.saml.key.KeyManager; import org.springframework.security.saml.metadata.*; @@ -31,7 +29,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Value("${saml.sp}") private String samlAudience; @@ -55,8 +53,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public SAMLDiscovery samlDiscovery() { - SAMLDiscovery idpDiscovery = new SAMLDiscovery(); - return idpDiscovery; + return new SAMLDiscovery(); } @Autowired @@ -78,19 +75,19 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { } @Bean - public SAMLProcessingFilter samlWebSSOProcessingFilter() throws Exception { + public SAMLProcessingFilter samlWebSSOProcessingFilter(AuthenticationManager authenticationManager) { SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter(); - samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager()); + samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager); samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(samlAuthSuccessHandler); samlWebSSOProcessingFilter.setAuthenticationFailureHandler(samlAuthFailureHandler); return samlWebSSOProcessingFilter; } @Bean - public FilterChainProxy samlFilter() throws Exception { + public FilterChainProxy samlFilter(SAMLProcessingFilter samlProcessingFilter) throws Exception { List chains = new ArrayList<>(); chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"), - samlWebSSOProcessingFilter())); + samlProcessingFilter)); chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"), samlDiscovery())); chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"), @@ -102,19 +99,13 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { return new FilterChainProxy(chains); } - @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - @Bean public MetadataGeneratorFilter metadataGeneratorFilter() { return new MetadataGeneratorFilter(metadataGenerator()); } - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http, SAMLProcessingFilter samlProcessingFilter) throws Exception { http .csrf() .disable(); @@ -125,8 +116,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { http .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class) - .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class) - .addFilterBefore(samlFilter(), CsrfFilter.class); + .addFilterAfter(samlProcessingFilter, BasicAuthenticationFilter.class) + .addFilterBefore(samlProcessingFilter, CsrfFilter.class); http .authorizeRequests() @@ -142,11 +133,10 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { e.printStackTrace(); } }); - } - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(samlAuthenticationProvider); + http.authenticationProvider(samlAuthenticationProvider); + + return http.build(); } } diff --git a/spring-security-modules/spring-security-saml2/pom.xml b/spring-security-modules/spring-security-saml2/pom.xml index 6de69fd201..64a4e22627 100644 --- a/spring-security-modules/spring-security-saml2/pom.xml +++ b/spring-security-modules/spring-security-saml2/pom.xml @@ -82,7 +82,6 @@ - 17 4.1.1 diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml index 08adb700ec..e93b0b4f03 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -45,8 +45,8 @@ spring-security-data - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/spring-security-modules/spring-security-web-boot-2/pom.xml b/spring-security-modules/spring-security-web-boot-2/pom.xml index 2255f8b035..d3684dd282 100644 --- a/spring-security-modules/spring-security-web-boot-2/pom.xml +++ b/spring-security-modules/spring-security-web-boot-2/pom.xml @@ -45,8 +45,8 @@ spring-security-data - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java index d3cfff81cb..0a9c717f5a 100644 --- a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java +++ b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java @@ -3,7 +3,6 @@ package com.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Spring Security Configuration. @@ -11,7 +10,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration @EnableWebSecurity @ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { public SecurityConfig() { super(); diff --git a/spring-shell/pom.xml b/spring-shell/pom.xml index 24fe5b0fb6..bdd495b836 100644 --- a/spring-shell/pom.xml +++ b/spring-shell/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 6c49f1f39c..c796b08e9a 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -102,7 +102,6 @@ - 17 4.0.0 3.1.0 0.15.3 diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index 95d3239b96..136f5b8907 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-swagger-codegen 0.0.1-SNAPSHOT - ../../parent-boot-2 @@ -83,12 +82,11 @@ - 11 3.0.0 2.17.1 1.7.0 3.3.4 - 2.10.0.pr3 + 2.16.0 5.1.0 diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index d4fff7eb63..ce28f28c22 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -16,6 +16,7 @@ + custom-validations-opeanpi-codegen spring-swagger-codegen-api-client spring-openapi-generator-api-client spring-swagger-codegen-app diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml index ee2c86238a..1e3b93ae42 100644 --- a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -276,7 +276,7 @@ 2.2 1.10 3.6.1 - 2.10.4 + 3.6.2 2.2.1 1.5 diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index 35f4978411..5ad15f6851 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -33,7 +33,6 @@ com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT - ../../spring-swagger-codegen @@ -196,7 +195,7 @@ 2.2 1.5 2.2.1 - 2.10.4 + 3.6.2 1.10 diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index d3f57474ef..a7969df518 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -10,7 +10,6 @@ com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT - ../../spring-swagger-codegen diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index b3690c7b7f..768303cb4b 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -83,7 +83,6 @@ 2.3.4 2.20.140 3.1.3 - 17 \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-2/pom.xml b/spring-web-modules/spring-mvc-basics-2/pom.xml index 613e42dee3..32cf3c9e9f 100644 --- a/spring-web-modules/spring-mvc-basics-2/pom.xml +++ b/spring-web-modules/spring-mvc-basics-2/pom.xml @@ -150,7 +150,7 @@ 8.0.1.Final enter-location-of-server - 3.0.11.RELEASE + 3.1.2.RELEASE 2.4.12 2.3.27-incubating 1.2.5 diff --git a/spring-web-modules/spring-mvc-forms-jsp/pom.xml b/spring-web-modules/spring-mvc-forms-jsp/pom.xml index 5096c6e23d..636551b555 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/pom.xml +++ b/spring-web-modules/spring-mvc-forms-jsp/pom.xml @@ -43,8 +43,8 @@ ${jstl.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -104,7 +104,7 @@ 8.0.1.Final 5.2.5.Final - 6.0.6 + 8.2.0 1.3.2 diff --git a/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml b/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml index eb31723798..9c9d6804ae 100644 --- a/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml @@ -27,6 +27,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/spring-web-modules/spring-mvc-java-2/README.md b/spring-web-modules/spring-mvc-java-2/README.md index 1f8231bada..61549b539a 100644 --- a/spring-web-modules/spring-mvc-java-2/README.md +++ b/spring-web-modules/spring-mvc-java-2/README.md @@ -5,3 +5,5 @@ - [A Quick Guide to Spring MVC Matrix Variables](https://www.baeldung.com/spring-mvc-matrix-variables) - [Converting a Spring MultipartFile to a File](https://www.baeldung.com/spring-multipartfile-to-file) - [Testing a Spring Multipart POST Request](https://www.baeldung.com/spring-multipart-post-request-test) +- [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit) +- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) diff --git a/spring-web-modules/spring-mvc-java-2/pom.xml b/spring-web-modules/spring-mvc-java-2/pom.xml index b1b5a797f8..a4484ed56d 100644 --- a/spring-web-modules/spring-mvc-java-2/pom.xml +++ b/spring-web-modules/spring-mvc-java-2/pom.xml @@ -46,6 +46,57 @@ commons-fileupload ${commons-fileupload.version} + + net.sourceforge.htmlunit + htmlunit + ${htmlunit.version} + + + commons-logging + commons-logging + + + commons-io + commons-io + + + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + org.glassfish + javax.el + ${javax.el.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax-servlet-api.version} + + + javax.servlet + jstl + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + @@ -63,6 +114,11 @@ 5.2.2.RELEASE 2.3.5 1.5 + 2.32 + 3.16-beta1 + 3.0.1-b09 + 2.3.3 + 3.0.9.RELEASE \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java similarity index 97% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java index f76f7441a5..5cb5de7124 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java @@ -1,18 +1,19 @@ -package com.baeldung.web.controller; +package com.baeldung.excel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import com.baeldung.excel.*; -import java.util.Map; -import java.util.List; -import javax.annotation.Resource; @Controller public class ExcelController { diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java index 0519a8f3c7..7a213d523b 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java @@ -1,13 +1,14 @@ package com.baeldung.excel; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; @@ -15,16 +16,15 @@ import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Map; -import java.util.HashMap; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.IntStream; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelPOIHelper { diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/MyCell.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/MyCell.java diff --git a/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java new file mode 100644 index 0000000000..f6a4d4dba3 --- /dev/null +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.excel; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "com.baeldung.excel" }) +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + + + @Bean + public ExcelPOIHelper excelPOIHelper() { + return new ExcelPOIHelper(); + } +} diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java similarity index 99% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java index 75efd57ae4..6e55f01454 100644 --- a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -20,7 +20,7 @@ public class TestConfig implements WebMvcConfigurer { @Autowired private ServletContext ctx; - + @Bean public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); @@ -44,4 +44,4 @@ public class TestConfig implements WebMvcConfigurer { templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } -} +} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java/README.md b/spring-web-modules/spring-mvc-java/README.md index 656e415f6a..d89f33fdc1 100644 --- a/spring-web-modules/spring-mvc-java/README.md +++ b/spring-web-modules/spring-mvc-java/README.md @@ -9,8 +9,6 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring ### Relevant Articles: - [Integration Testing in Spring](https://www.baeldung.com/integration-testing-in-spring) - [File Upload with Spring MVC](https://www.baeldung.com/spring-file-upload) -- [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit) -- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) - [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) diff --git a/spring-web-modules/spring-mvc-java/pom.xml b/spring-web-modules/spring-mvc-java/pom.xml index 395b12a278..d4c8f24431 100644 --- a/spring-web-modules/spring-mvc-java/pom.xml +++ b/spring-web-modules/spring-mvc-java/pom.xml @@ -44,21 +44,7 @@ provided - - net.sourceforge.htmlunit - htmlunit - ${htmlunit.version} - - - commons-logging - commons-logging - - - commons-io - commons-io - - - + commons-io commons-io @@ -91,12 +77,7 @@ spring-boot-starter-test test - - - org.apache.poi - poi-ooxml - ${poi.version} - + org.hibernate.validator @@ -221,19 +202,15 @@ 4.4.5 4.5.2 - 2.23 2.7 1.6.1 3.1.0 1.9.1 - - 3.16-beta1 3.0.1-b09 4.0.1 2.3.3 - 2.32 2.8.0 com.baeldung.SpringMVCApplication diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 768fda1c4a..c135164a95 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -27,7 +27,6 @@ import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ITemplateResolver; -import com.baeldung.excel.ExcelPOIHelper; @EnableWebMvc @Configuration @@ -118,11 +117,6 @@ public class WebConfig implements WebMvcConfigurer { configurer.setUrlPathHelper(urlPathHelper); } - @Bean - public ExcelPOIHelper excelPOIHelper() { - return new ExcelPOIHelper(); - } - @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); diff --git a/spring-web-modules/spring-rest-http-2/pom.xml b/spring-web-modules/spring-rest-http-2/pom.xml index bcacdbbdb1..c6c8cd2010 100644 --- a/spring-web-modules/spring-rest-http-2/pom.xml +++ b/spring-web-modules/spring-rest-http-2/pom.xml @@ -51,7 +51,7 @@ 2.9.2 - 1.6.1 + 2.1.0 1.7.0 diff --git a/spring-web-modules/spring-rest-query-language/pom.xml b/spring-web-modules/spring-rest-query-language/pom.xml index 987d678439..b44972603d 100644 --- a/spring-web-modules/spring-rest-query-language/pom.xml +++ b/spring-web-modules/spring-rest-query-language/pom.xml @@ -140,8 +140,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml index 67b3115a6f..db1ec6c165 100644 --- a/spring-web-modules/spring-rest-testing/pom.xml +++ b/spring-web-modules/spring-rest-testing/pom.xml @@ -103,8 +103,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/spring-web-modules/spring-session/spring-session-jdbc/pom.xml b/spring-web-modules/spring-session/spring-session-jdbc/pom.xml index 3cc2b8d18e..24194f5426 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/pom.xml +++ b/spring-web-modules/spring-session/spring-session-jdbc/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 diff --git a/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java b/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java index 509a5f292b..a173636ed8 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java +++ b/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java @@ -7,11 +7,12 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; + @Controller public class SpringSessionJdbcController { diff --git a/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java b/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java index 2dcc0b3af8..7133111e4c 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java +++ b/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; diff --git a/spring-web-modules/spring-thymeleaf-5/pom.xml b/spring-web-modules/spring-thymeleaf-5/pom.xml index 2d178bd933..e6b0511ce5 100644 --- a/spring-web-modules/spring-thymeleaf-5/pom.xml +++ b/spring-web-modules/spring-thymeleaf-5/pom.xml @@ -135,7 +135,7 @@ 2.3.2.RELEASE - 3.0.11.RELEASE + 3.1.2.RELEASE 3.0.4.RELEASE 2.4.1 2.0.1.Final diff --git a/spring-web-modules/spring-thymeleaf/pom.xml b/spring-web-modules/spring-thymeleaf/pom.xml index ce0c0a7e21..ca94d4581e 100644 --- a/spring-web-modules/spring-thymeleaf/pom.xml +++ b/spring-web-modules/spring-thymeleaf/pom.xml @@ -136,7 +136,7 @@ 2.3.2.RELEASE - 3.0.11.RELEASE + 3.1.2.RELEASE 3.0.4.RELEASE 2.4.1 2.0.1.Final diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java index ea51ca3cd9..074cc20be1 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java +++ b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -2,42 +2,37 @@ package com.baeldung.thymeleaf.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) -public class WebMVCSecurity extends WebSecurityConfigurerAdapter { +public class WebMVCSecurity { @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); + public InMemoryUserDetailsManager userDetailsService() { + UserDetails user = User.withUsername("user1") + .password("{noop}user1Pass") + .authorities("USER") + .build(); + return new InMemoryUserDetailsManager(user); } - public WebMVCSecurity() { - super(); + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> web.ignoring().antMatchers("/resources/**"); } - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER"); - } - - @Override - public void configure(final WebSecurity web) throws Exception { - web.ignoring().antMatchers("/resources/**"); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); + @Bean + public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception { + return http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().build(); } } diff --git a/spring-websockets/pom.xml b/spring-websockets/pom.xml index a28ef8749a..6ca84c4946 100644 --- a/spring-websockets/pom.xml +++ b/spring-websockets/pom.xml @@ -26,7 +26,7 @@ com.github.javafaker javafaker - 1.0.2 + ${javafaker.version} com.google.code.gson @@ -44,4 +44,8 @@ + + 1.0.2 + + \ No newline at end of file diff --git a/static-analysis/README.md b/static-analysis/README.md index 235b79853b..ea0d797407 100644 --- a/static-analysis/README.md +++ b/static-analysis/README.md @@ -6,3 +6,4 @@ This module contains articles about static program analysis - [Introduction to PMD](https://www.baeldung.com/pmd) - [Java Static Analysis Tools in Eclipse and IntelliJ IDEA](https://www.baeldung.com/java-static-analysis-tools) +- [Catch Common Mistakes with Error Prone Library in Java](https://www.baeldung.com/java-error-prone-library) diff --git a/static-analysis/error-prone-project/.mvn/jvm.config b/static-analysis/error-prone-project/.mvn/jvm.config new file mode 100644 index 0000000000..32599cefea --- /dev/null +++ b/static-analysis/error-prone-project/.mvn/jvm.config @@ -0,0 +1,10 @@ +--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED diff --git a/static-analysis/error-prone-project/pom.xml b/static-analysis/error-prone-project/pom.xml new file mode 100644 index 0000000000..2d5706d0d2 --- /dev/null +++ b/static-analysis/error-prone-project/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + error-prone-project + + + com.baeldung + static-analysis + 1.0-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 17 + true + + -XDcompilePolicy=simple + -Xplugin:ErrorProne + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + com.google.errorprone + error_prone_core + ${error-prone.version} + + + com.baeldung + my-bugchecker-plugin + ${my-bugchecker-plugin.version} + + + + + + + + + 1.0-SNAPSHOT + + + diff --git a/static-analysis/error-prone-project/src/main/java/com/baeldung/BuggyClass.java b/static-analysis/error-prone-project/src/main/java/com/baeldung/BuggyClass.java new file mode 100644 index 0000000000..dda432ad48 --- /dev/null +++ b/static-analysis/error-prone-project/src/main/java/com/baeldung/BuggyClass.java @@ -0,0 +1,12 @@ +package com.baeldung; + +public class BuggyClass { + public static void main(String[] args) { + if (args.length == 0 || args[0] != null) { + new IllegalArgumentException(); + } + } + + public void emptyMethod() { + } +} diff --git a/static-analysis/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java b/static-analysis/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java new file mode 100644 index 0000000000..cc791ecdd4 --- /dev/null +++ b/static-analysis/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java @@ -0,0 +1,6 @@ +package com.baeldung; + +public class ClassWithEmptyMethod { + public void theEmptyMethod() { + } +} diff --git a/static-analysis/my-bugchecker-plugin/pom.xml b/static-analysis/my-bugchecker-plugin/pom.xml new file mode 100644 index 0000000000..eb11f07b4e --- /dev/null +++ b/static-analysis/my-bugchecker-plugin/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + my-bugchecker-plugin + jar + + + com.baeldung + static-analysis + 1.0-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + + com.google.auto.service + auto-service + ${google-auto-service.version} + + + + + + + + + com.google.errorprone + error_prone_annotation + ${error-prone.version} + + + com.google.errorprone + error_prone_check_api + ${error-prone.version} + + + com.google.auto.service + auto-service-annotations + ${google-auto-service.version} + + + + diff --git a/static-analysis/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java b/static-analysis/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java new file mode 100644 index 0000000000..f31913c086 --- /dev/null +++ b/static-analysis/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java @@ -0,0 +1,24 @@ +package com.baeldung; + +import com.google.auto.service.AutoService; +import com.google.errorprone.BugPattern; +import com.google.errorprone.VisitorState; +import com.google.errorprone.bugpatterns.BugChecker; +import com.google.errorprone.fixes.SuggestedFix; +import com.google.errorprone.matchers.Description; +import com.sun.source.tree.MethodTree; + + +@AutoService(BugChecker.class) +@BugPattern(name = "EmptyMethodCheck", summary = "Empty methods should be deleted", severity = BugPattern.SeverityLevel.ERROR) +public class EmptyMethodChecker extends BugChecker implements BugChecker.MethodTreeMatcher { + @Override + public Description matchMethod(MethodTree methodTree, VisitorState visitorState) { + if (methodTree.getBody() + .getStatements() + .isEmpty()) { + return describeMatch(methodTree, SuggestedFix.delete(methodTree)); + } + return Description.NO_MATCH; + } +} diff --git a/static-analysis/pmd/pom.xml b/static-analysis/pmd/pom.xml new file mode 100644 index 0000000000..372c122776 --- /dev/null +++ b/static-analysis/pmd/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + pmd + + + com.baeldung + static-analysis + 1.0-SNAPSHOT + + + diff --git a/static-analysis/src/main/java/com/baeldung/pmd/Cnt.java b/static-analysis/pmd/src/main/java/com/baeldung/pmd/Cnt.java similarity index 100% rename from static-analysis/src/main/java/com/baeldung/pmd/Cnt.java rename to static-analysis/pmd/src/main/java/com/baeldung/pmd/Cnt.java diff --git a/static-analysis/src/main/resources/customruleset.xml b/static-analysis/pmd/src/main/resources/customruleset.xml similarity index 97% rename from static-analysis/src/main/resources/customruleset.xml rename to static-analysis/pmd/src/main/resources/customruleset.xml index e0a009dd4a..6b1a80334d 100644 --- a/static-analysis/src/main/resources/customruleset.xml +++ b/static-analysis/pmd/src/main/resources/customruleset.xml @@ -1,37 +1,37 @@ - - - - - This ruleset checks my code for bad stuff - - - - - - - - - - - - - - 2 - - - - - - - - - - - - - - + + + + + This ruleset checks my code for bad stuff + + + + + + + + + + + + + + 2 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/static-analysis/src/main/resources/logback.xml b/static-analysis/pmd/src/main/resources/logback.xml similarity index 100% rename from static-analysis/src/main/resources/logback.xml rename to static-analysis/pmd/src/main/resources/logback.xml diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java b/static-analysis/pmd/src/test/java/com/baeldung/pmd/CntUnitTest.java similarity index 100% rename from static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java rename to static-analysis/pmd/src/test/java/com/baeldung/pmd/CntUnitTest.java diff --git a/static-analysis/pom.xml b/static-analysis/pom.xml index eedf5ba724..176f3dc092 100644 --- a/static-analysis/pom.xml +++ b/static-analysis/pom.xml @@ -6,6 +6,7 @@ static-analysis 1.0-SNAPSHOT static-analysis + pom com.baeldung @@ -29,4 +30,15 @@ - \ No newline at end of file + + pmd + my-bugchecker-plugin + error-prone-project + + + + 2.23.0 + 1.0.1 + + + diff --git a/tablesaw/pom.xml b/tablesaw/pom.xml index f38e4cb8b4..c45931a9e2 100644 --- a/tablesaw/pom.xml +++ b/tablesaw/pom.xml @@ -25,11 +25,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 - - 17 - 17 - diff --git a/testing-modules/cucumber/pom.xml b/testing-modules/cucumber/pom.xml index 6d178b86a3..088a75a941 100644 --- a/testing-modules/cucumber/pom.xml +++ b/testing-modules/cucumber/pom.xml @@ -42,6 +42,7 @@ org.projectlombok lombok provided + ${lombok.version} io.cucumber @@ -120,8 +121,6 @@ - 14 - 14 6.10.3 5.4.0 3.141.59 diff --git a/testing-modules/gatling-java/pom.xml b/testing-modules/gatling-java/pom.xml index abe033f298..54dee1fd88 100644 --- a/testing-modules/gatling-java/pom.xml +++ b/testing-modules/gatling-java/pom.xml @@ -72,9 +72,6 @@ - 1.8 - 1.8 - UTF-8 3.9.5 4.3.0 1.0.2 diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 82ce988bac..e5b1db2bfb 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -105,9 +105,6 @@ - 1.8 - 1.8 - UTF-8 2.12.6 3.3.1 4.3.0 diff --git a/testing-modules/jqwik/pom.xml b/testing-modules/jqwik/pom.xml index 6ef9b61a6a..85c4ba571a 100644 --- a/testing-modules/jqwik/pom.xml +++ b/testing-modules/jqwik/pom.xml @@ -17,7 +17,7 @@ net.jqwik jqwik - 1.7.4 + ${jqwik.version} test @@ -53,5 +53,9 @@ + + 1.7.4 + + diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index 411f189638..fc0349ff8e 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/pom.xml @@ -18,7 +18,7 @@ com.github.stefanbirkner system-lambda - 1.2.1 + ${system-lambda.version} test @@ -79,6 +79,7 @@ + 1.2.1 1.49 3.24.2 1.10.1 diff --git a/testing-modules/junit-5-basics-2/pom.xml b/testing-modules/junit-5-basics-2/pom.xml index b430161380..f03b74f47a 100644 --- a/testing-modules/junit-5-basics-2/pom.xml +++ b/testing-modules/junit-5-basics-2/pom.xml @@ -36,18 +36,11 @@ org.apache.maven.plugins maven-compiler-plugin - - 11 - 11 - - 11 - 11 - UTF-8 1.5.0 5.10.0 5.5.0 diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index 8afaa085b1..cdddf90855 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -107,7 +107,6 @@ org.codehaus.mojo exec-maven-plugin - ${exec-maven-plugin.version} diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index d5a389d311..af42523ca9 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -66,9 +66,6 @@ - 1.8 - 1.8 - UTF-8 2.12.12 3.4.0 4.4.0 diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 0e0f19b6b3..100c9d7015 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -21,9 +21,6 @@ - 8 - 8 - UTF-8 4.8.1 diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java b/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java new file mode 100644 index 0000000000..bc6274eb18 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java @@ -0,0 +1,26 @@ +package com.baeldung.lambdacalls; + +import java.util.ArrayList; + +public class LambdaExample { + + private BrickLayer brickLayer = new BrickLayer(); + + static ArrayList bricksList = new ArrayList<>(); + + public void createWall(String bricks){ + Runnable build = () -> brickLayer.layBricks(bricks); + build.run(); + } + + public ArrayList getBricksList(){ + return bricksList; + } + + static class BrickLayer { + void layBricks(String bricks){ + bricksList.add(bricks); + } + } + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java new file mode 100644 index 0000000000..67127c641c --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.lambdacalls; + +import static com.baeldung.lambdacalls.LambdaExample.*; +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class LambdaCallsUnitTest { + + @Mock + private/**/ BrickLayer brickLayer; + @InjectMocks + private LambdaExample lambdaExample; + + @Test + public void whenCallingALambda_thenTheInvocationCanBeConfirmedWithCorrectArguments(){ + String bricks = "red bricks"; + lambdaExample.createWall(bricks); + verify(brickLayer).layBricks(bricks); + } + + @Test + public void whenCallingALambda_thenCorrectBehaviourIsPerformed(){ + LambdaExample lambdaExample = new LambdaExample(); + String bricks = "red bricks"; + + lambdaExample.createWall(bricks); + ArrayList bricksList = lambdaExample.getBricksList(); + + assertEquals(bricks, bricksList.get(0)); + } + +} diff --git a/testing-modules/mocks-2/pom.xml b/testing-modules/mocks-2/pom.xml index 22a5198b8c..2ef1a03dff 100644 --- a/testing-modules/mocks-2/pom.xml +++ b/testing-modules/mocks-2/pom.xml @@ -33,7 +33,7 @@ 1.6.0 - 2.13.4 + 2.16.0 5.3.25 diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index fa72b1e696..b2e73570d5 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -34,8 +34,8 @@ load-testing-comparison mockito - mocks - mocks-2 + + mockserver parallel-tests-junit powermock diff --git a/testing-modules/spring-mockito/pom.xml b/testing-modules/spring-mockito/pom.xml index 6283ea2d1f..8e13f511d2 100644 --- a/testing-modules/spring-mockito/pom.xml +++ b/testing-modules/spring-mockito/pom.xml @@ -29,6 +29,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/testing-modules/testing-assertions/README.md b/testing-modules/testing-assertions/README.md index 8f94277791..3e529bc1d3 100644 --- a/testing-modules/testing-assertions/README.md +++ b/testing-modules/testing-assertions/README.md @@ -6,3 +6,4 @@ - [Assert That an Object Is From a Specific Type](https://www.baeldung.com/java-assert-object-of-type) - [Asserting Equality on Two Classes Without an equals() Method](https://www.baeldung.com/java-assert-equality-no-equals) - [Assert Regex Matches in JUnit](https://www.baeldung.com/junit-assert-regex-matches) +- [Asserting Nested Map With JUnit](https://www.baeldung.com/junit-assert-nested-map) diff --git a/timefold-solver/README.md b/timefold-solver/README.md new file mode 100644 index 0000000000..1abc4d4ca0 --- /dev/null +++ b/timefold-solver/README.md @@ -0,0 +1,6 @@ +## Timefold Solver + +This module contains articles about (Timefold Solver)[https://timefold.ai]. + +### Relevant articles + diff --git a/timefold-solver/pom.xml b/timefold-solver/pom.xml new file mode 100644 index 0000000000..a16afb9e54 --- /dev/null +++ b/timefold-solver/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + timefold-solver + timefold-solver + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + ai.timefold.solver + timefold-solver-bom + ${version.ai.timefold.solver} + pom + import + + + + + + ai.timefold.solver + timefold-solver-core + + + ai.timefold.solver + timefold-solver-test + test + + + + + 17 + 17 + 1.4.0 + + + diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java new file mode 100644 index 0000000000..ef4752a8c6 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java @@ -0,0 +1,28 @@ +package com.baeldung.timefoldsolver; + +import java.util.Set; + +public class Employee { + + private String name; + private Set skills; + + public Employee(String name, Set skills) { + this.name = name; + this.skills = skills; + } + + @Override + public String toString() { + return name; + } + + public String getName() { + return name; + } + + public Set getSkills() { + return skills; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java new file mode 100644 index 0000000000..2ef2f2a1b9 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java @@ -0,0 +1,54 @@ +package com.baeldung.timefoldsolver; + +import java.time.LocalDateTime; + +import ai.timefold.solver.core.api.domain.entity.PlanningEntity; +import ai.timefold.solver.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Shift { + + private LocalDateTime start; + private LocalDateTime end; + private String requiredSkill; + + @PlanningVariable + private Employee employee; + + // A no-arg constructor is required for @PlanningEntity annotated classes + public Shift() { + } + + public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill) { + this(start, end, requiredSkill, null); + } + + public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill, Employee employee) { + this.start = start; + this.end = end; + this.requiredSkill = requiredSkill; + this.employee = employee; + } + + @Override + public String toString() { + return start + " - " + end; + } + + public LocalDateTime getStart() { + return start; + } + + public LocalDateTime getEnd() { + return end; + } + + public String getRequiredSkill() { + return requiredSkill; + } + + public Employee getEmployee() { + return employee; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java new file mode 100644 index 0000000000..794c31e5b7 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java @@ -0,0 +1,43 @@ +package com.baeldung.timefoldsolver; + +import java.util.List; + +import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty; +import ai.timefold.solver.core.api.domain.solution.PlanningScore; +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; + +@PlanningSolution +public class ShiftSchedule { + + @ValueRangeProvider + private List employees; + @PlanningEntityCollectionProperty + private List shifts; + + @PlanningScore + private HardSoftScore score; + + // A no-arg constructor is required for @PlanningSolution annotated classes + public ShiftSchedule() { + } + + public ShiftSchedule(List employees, List shifts) { + this.employees = employees; + this.shifts = shifts; + } + + public List getEmployees() { + return employees; + } + + public List getShifts() { + return shifts; + } + + public HardSoftScore getScore() { + return score; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java new file mode 100644 index 0000000000..bd308dacbf --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java @@ -0,0 +1,35 @@ +package com.baeldung.timefoldsolver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; + +public class ShiftScheduleConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { atMostOneShiftPerDay(constraintFactory), requiredSkill(constraintFactory) }; + } + + public Constraint atMostOneShiftPerDay(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Shift.class) + .join(Shift.class, equal(shift -> shift.getStart() + .toLocalDate()), equal(Shift::getEmployee)) + .filter((shift1, shift2) -> shift1 != shift2) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("At most one shift per day"); + } + + public Constraint requiredSkill(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Shift.class) + .filter(shift -> !shift.getEmployee() + .getSkills() + .contains(shift.getRequiredSkill())) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("Required skill"); + } + +} diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java new file mode 100644 index 0000000000..c8ec5b53c4 --- /dev/null +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.timefoldsolver; + +import java.time.LocalDate; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import ai.timefold.solver.test.api.score.stream.ConstraintVerifier; + +class ShiftScheduleConstraintProviderUnitTest { + + private static final LocalDate MONDAY = LocalDate.of(2030, 4, 1); + private static final LocalDate TUESDAY = LocalDate.of(2030, 4, 2); + + ConstraintVerifier constraintVerifier = ConstraintVerifier.build(new ShiftScheduleConstraintProvider(), + ShiftSchedule.class, Shift.class); + + @Test + void givenTwoShiftsOnOneDay_whenApplyingAtMostOneShiftPerDayConstraint_thenPenalize() { + Employee ann = new Employee("Ann", null); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) + // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. + // To avoid that, use forEachUniquePair(Shift) instead of forEach(Shift).join(Shift) in ShiftScheduleConstraintProvider.atMostOneShiftPerDay(). + .penalizesBy(2); + } + + @Test + void givenTwoShiftsOnDifferentDays_whenApplyingAtMostOneShiftPerDayConstraint_thenDoNotPenalize() { + Employee ann = new Employee("Ann", null); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(TUESDAY.atTime(14, 0), TUESDAY.atTime(22, 0), null, ann)) + .penalizesBy(0); + } + + @Test + void givenEmployeeLacksRequiredSkill_whenApplyingRequiredSkillConstraint_thenPenalize() { + Employee ann = new Employee("Ann", Set.of("Waiter")); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Cook", ann)) + .penalizesBy(1); + } + + @Test + void givenEmployeeHasRequiredSkill_whenApplyingRequiredSkillConstraint_thenDoNotPenalize() { + Employee ann = new Employee("Ann", Set.of("Waiter")); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Waiter", ann)) + .penalizesBy(0); + } + +} diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java new file mode 100644 index 0000000000..873ce1a853 --- /dev/null +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.timefoldsolver; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.time.Duration; +import java.time.LocalDate; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.solver.Solver; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.SolverConfig; +import ai.timefold.solver.core.config.solver.termination.TerminationConfig; + +public class ShiftScheduleSolverUnitTest { + + private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleSolverUnitTest.class); + + @Test + public void given3Employees5Shifts_whenSolve_thenScoreIsOptimalAndAllShiftsAssigned() { + SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) + .withEntityClasses(Shift.class) + .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) + // For this dataset, we know the optimal score in advance (which is normally not the case). + // So we can use .withBestScoreLimit() instead of .withTerminationSpentLimit(). + .withTerminationConfig(new TerminationConfig().withBestScoreLimit("0hard/0soft"))); + Solver solver = solverFactory.buildSolver(); + + ShiftSchedule problem = loadProblem(); + ShiftSchedule solution = solver.solve(problem); + assertThat(solution.getScore()).isEqualTo(HardSoftScore.ZERO); + assertThat(solution.getShifts().size()).isNotZero(); + for (Shift shift : solution.getShifts()) { + assertThat(shift.getEmployee()).isNotNull(); + } + printSolution(solution); + } + + private ShiftSchedule loadProblem() { + LocalDate monday = LocalDate.of(2030, 4, 1); + LocalDate tuesday = LocalDate.of(2030, 4, 2); + return new ShiftSchedule( + List.of(new Employee("Ann", Set.of("Bartender")), new Employee("Beth", Set.of("Waiter", "Bartender")), new Employee("Carl", Set.of("Waiter"))), + List.of(new Shift(monday.atTime(6, 0), monday.atTime(14, 0), "Waiter"), new Shift(monday.atTime(9, 0), monday.atTime(17, 0), "Bartender"), + new Shift(monday.atTime(14, 0), monday.atTime(22, 0), "Bartender"), new Shift(tuesday.atTime(6, 0), tuesday.atTime(14, 0), "Waiter"), + new Shift(tuesday.atTime(14, 0), tuesday.atTime(22, 0), "Bartender"))); + } + + private void printSolution(ShiftSchedule solution) { + logger.info("Shift assignments"); + for (Shift shift : solution.getShifts()) { + logger.info(" " + shift.getStart() + .toLocalDate() + " " + shift.getStart() + .toLocalTime() + " - " + shift.getEnd() + .toLocalTime() + ": " + shift.getEmployee() + .getName()); + } + } + +} diff --git a/vavr-modules/java-vavr-stream/pom.xml b/vavr-modules/java-vavr-stream/pom.xml index cda9d1f734..e369fa7cf3 100644 --- a/vavr-modules/java-vavr-stream/pom.xml +++ b/vavr-modules/java-vavr-stream/pom.xml @@ -19,12 +19,8 @@ io.vavr vavr - ${io.vavr.version} + ${vavr.version} - - 0.9.2 - - \ No newline at end of file diff --git a/vavr-modules/pom.xml b/vavr-modules/pom.xml index 416c689511..e9a3b121aa 100644 --- a/vavr-modules/pom.xml +++ b/vavr-modules/pom.xml @@ -30,4 +30,8 @@ + + 0.9.2 + + \ No newline at end of file diff --git a/vavr-modules/vavr-2/pom.xml b/vavr-modules/vavr-2/pom.xml index 0063daa518..54f3cb4d71 100644 --- a/vavr-modules/vavr-2/pom.xml +++ b/vavr-modules/vavr-2/pom.xml @@ -21,8 +21,4 @@ - - 0.9.1 - - \ No newline at end of file diff --git a/vertx-modules/pom.xml b/vertx-modules/pom.xml index 7d9614ad61..00f0bc46f5 100644 --- a/vertx-modules/pom.xml +++ b/vertx-modules/pom.xml @@ -30,4 +30,8 @@ + + 3.9.15 + + \ No newline at end of file diff --git a/vertx-modules/vertx-and-rxjava/pom.xml b/vertx-modules/vertx-and-rxjava/pom.xml index 16eaf8ebaa..b68117ddeb 100644 --- a/vertx-modules/vertx-and-rxjava/pom.xml +++ b/vertx-modules/vertx-and-rxjava/pom.xml @@ -40,8 +40,4 @@ - - 3.9.15 - - \ No newline at end of file diff --git a/vertx-modules/vertx/pom.xml b/vertx-modules/vertx/pom.xml index 75df2fae69..d34deca9d8 100644 --- a/vertx-modules/vertx/pom.xml +++ b/vertx-modules/vertx/pom.xml @@ -65,7 +65,6 @@ - 3.9.15 3.2.1 diff --git a/web-modules/apache-tapestry/pom.xml b/web-modules/apache-tapestry/pom.xml index 562cdff00c..bfc7c22415 100644 --- a/web-modules/apache-tapestry/pom.xml +++ b/web-modules/apache-tapestry/pom.xml @@ -78,17 +78,13 @@ org.apache.maven.plugins maven-compiler-plugin - ${compiler.plugin.version} - ${source.version} - ${target.version} true org.apache.maven.plugins maven-surefire-plugin - ${compiler.surefire.version} Qa @@ -118,7 +114,6 @@ org.apache.maven.plugins maven-war-plugin - 3.3.1 @@ -140,9 +135,6 @@ 6.1.16 3.0.0-M5 - 3.8.1 - 11 - 11 5.8.2 2.5 6.8.21 diff --git a/web-modules/blade/pom.xml b/web-modules/blade/pom.xml index 2748c05663..fb0ca13dbe 100644 --- a/web-modules/blade/pom.xml +++ b/web-modules/blade/pom.xml @@ -62,7 +62,6 @@ org.apache.maven.plugins maven-failsafe-plugin - ${maven-failsafe-plugin.version} true diff --git a/web-modules/jakarta-ee/pom.xml b/web-modules/jakarta-ee/pom.xml index 066bc14766..d90e848323 100644 --- a/web-modules/jakarta-ee/pom.xml +++ b/web-modules/jakarta-ee/pom.xml @@ -2,7 +2,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung jakarta-ee 1.0-SNAPSHOT jakarta-ee @@ -51,7 +50,7 @@ org.glassfish.maven.plugin maven-glassfish-plugin - 2.1 + ${maven-glassfish-plugin.version} ${local.glassfish.home} admin @@ -76,11 +75,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 - - 11 - 11 - org.apache.maven.plugins @@ -104,6 +98,7 @@ ${local.glassfish.home}\\domains\\${local.glassfish.domain}\\config\\domain-passwords + 2.1 \ No newline at end of file diff --git a/web-modules/java-lite/pom.xml b/web-modules/java-lite/pom.xml index 7f1c9182f7..be079d484e 100644 --- a/web-modules/java-lite/pom.xml +++ b/web-modules/java-lite/pom.xml @@ -22,8 +22,8 @@ ${activeweb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.java.version} @@ -88,7 +88,7 @@ 9.4.8.v20171121 1.4.13 1.15 - 5.1.45 + 8.2.0 1.7.0 1.15 diff --git a/web-modules/vraptor/pom.xml b/web-modules/vraptor/pom.xml index 25f8b5d5e5..d952cd71e5 100644 --- a/web-modules/vraptor/pom.xml +++ b/web-modules/vraptor/pom.xml @@ -80,8 +80,8 @@ ${vraptor-hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector.version} @@ -118,7 +118,7 @@ 8.0.1.Final 4.1.0-RC3 4.0.4 - 8.0.8-dmr + 8.2.0 0.4 2.3.27-incubating 2.1 diff --git a/xml-2/README.md b/xml-2/README.md index e9c1a07586..a6762f2840 100644 --- a/xml-2/README.md +++ b/xml-2/README.md @@ -9,3 +9,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Converting JSON to XML in Java](https://www.baeldung.com/java-convert-json-to-xml) - [Convert an XML Object to a String in Java](https://www.baeldung.com/java-convert-xml-object-string) - [Convert String Containing XML to org.w3c.dom.Document](https://www.baeldung.com/java-convert-string-xml-dom) +- [How to Parse XML to HashMap in Java](https://www.baeldung.com/java-xml-read-into-hashmap) diff --git a/xml/README.md b/xml/README.md index 16942c6836..596ddc14aa 100644 --- a/xml/README.md +++ b/xml/README.md @@ -13,3 +13,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Parsing an XML File Using StAX](https://www.baeldung.com/java-stax) - [Parsing an XML File Using SAX Parser](https://www.baeldung.com/java-sax-parser) - [Remove HTML Tags Using Java](https://www.baeldung.com/java-remove-html-tags) +- [Convert an XML File to CSV File](https://www.baeldung.com/java-convert-xml-csv) diff --git a/xml/pom.xml b/xml/pom.xml index b56b919914..785634e265 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -372,7 +372,7 @@ 0.9.6 1.3.1 - 1.14.3 + 1.16.2 2.25 3.4 6.7.0 diff --git a/xml/src/main/java/com/baeldung/xml/DefaultParser.java b/xml/src/main/java/com/baeldung/xml/DefaultParser.java index 83280aa0f2..63e4a453c3 100644 --- a/xml/src/main/java/com/baeldung/xml/DefaultParser.java +++ b/xml/src/main/java/com/baeldung/xml/DefaultParser.java @@ -163,10 +163,10 @@ public class DefaultParser { private void clean(Node node) { - NodeList childs = node.getChildNodes(); + NodeList childNodes = node.getChildNodes(); - for (int n = childs.getLength() - 1; n >= 0; n--) { - Node child = childs.item(n); + for (int n = childNodes.getLength() - 1; n >= 0; n--) { + Node child = childNodes.item(n); short nodeType = child.getNodeType(); if (nodeType == Node.ELEMENT_NODE) diff --git a/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java b/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java index 99e5c7c0cb..84098b33f8 100644 --- a/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java +++ b/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java @@ -40,7 +40,7 @@ public class Xml2CsvExample { protected static void convertXml2CsvXslt(String xslPath, String xmlPath, String csvPath) throws IOException, TransformerException { StreamSource styleSource = new StreamSource(new File(xslPath)); Transformer transformer = TransformerFactory.newInstance() - .newTransformer(styleSource); + .newTransformer(styleSource); Source source = new StreamSource(new File(xmlPath)); Result outputTarget = new StreamResult(new File(csvPath)); transformer.transform(source, outputTarget); @@ -68,26 +68,26 @@ public class Xml2CsvExample { if ("Bookstore".equals(currentElement)) { bookstoreInfo.setLength(0); bookstoreInfo.append(reader.getAttributeValue(null, "id")) - .append(","); + .append(","); } if ("Book".equals(currentElement)) { csvRow.append(bookstoreInfo) - .append(reader.getAttributeValue(null, "id")) - .append(",") - .append(reader.getAttributeValue(null, "category")) - .append(","); + .append(reader.getAttributeValue(null, "id")) + .append(",") + .append(reader.getAttributeValue(null, "category")) + .append(","); } if ("Author".equals(currentElement)) { csvRow.append(reader.getAttributeValue(null, "id")) - .append(","); + .append(","); } break; case XMLStreamConstants.CHARACTERS: if (!reader.isWhiteSpace()) { csvRow.append(reader.getText() - .trim()) - .append(","); + .trim()) + .append(","); } break; diff --git a/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java b/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java index 3fa44b427c..181d284b2d 100644 --- a/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java +++ b/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java @@ -91,7 +91,7 @@ public class Xml2CsvExampleUnitTest { Xml2CsvExample.convertXml2CsvXslt(STYLE_XSL, DATA_XML, TEMP_OUTPUT_CSV); File csvFile = new File(TEMP_OUTPUT_CSV); - try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { + try (BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { String line; boolean isFirstLine = true; while ((line = reader.readLine()) != null) { @@ -113,7 +113,7 @@ public class Xml2CsvExampleUnitTest { Xml2CsvExample.convertXml2CsvStax(DATA_XML, TEMP_OUTPUT_CSV); File csvFile = new File(TEMP_OUTPUT_CSV); - try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { + try (BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { String line; boolean isFirstLine = true; while ((line = reader.readLine()) != null) {